highlight word in div using javascript - html

hi i have to implement find and replace functionality in my project. in this functionality there is one find and replace button on the top of contenteditable div. when user click on this button, popup window will open and ask for the search word when specify word and press find it will find word in that div only. and if match found it will highlight that word. so anybody tell me how can i highlight word in div. its urgent so please . thank you.
<div id="test" contenteditable="true">
this is test <font class='classname'> some text test</font>
</div>
i want to high light only test word not else

You will need to search through the div to find the word and then put that word into a span, and change the background color of the span.
Edit: I just noticed that you are not using CSS, so you will need to insert a font tag to change the color.

I just stole this from Sphix, the documentation tool:
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery.className.has(node.parentNode, className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this)
});
}
}
return this.each(function() {
highlight(this);
});
}
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('.sidebar .this-page-menu li.highlight-link').fadeOut(300);
$('span.highlight').removeClass('highlight');
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
},
So, adding this to a js file in your site, any page with it that receives a highlight GET parameter will search and highlight the word in the page.
You can find a demo of the working code in:
http://sphinx.pocoo.org/intro.html?highlight=python
Note: This code needs jQuery, off course...

Its actually pretty easy using the prototype library:
<html>
<head>
<style type="text/css">
#content span {
background-color: yellow;
}
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
var htm = $('content').innerHTML;
$('content').innerHTML = htm.sub('my','<span>my</span>');
});
</script>
</head>
<body>
<div id="content">
This is the div containing my content.
</div>
</body>
</html>
This should get you started so you can implement the rest.

To highlight a word you have to select it somehow. One option is to surround the word with a span tag.
this is <span class="highlight">test</span> some text test
then specify CSS for the highlight class.

Related

How to change CSS that Django template uses with a button?

I am trying to implement accessibility option on my page that would change CSS to different file when accessibility button would be clicked.
For now, all my templates extends base_generic.html, where style.css is loaded. When accessibility button would be clicked, I wish for it to change to use style_access.css for that user. How can I accomplish that?
I think a way could be, to refer in the HTML template to both CSS files, and use an onclick function with javascript, and jquery to change the id or class of the specific elements of the template.
So for example,
let's say I wanted onclick to change the CSS of an element, I could make a counter and toggle between two ids that I will have referenced in my CSS file or files.
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<button>This is a div</button>
<h1 class="potatoe" id="hello">HELLO THIS IS TEXT</h1>
<style>
#hello { color: red; }
#bye { color: blue; }
</style>
<script>
var clickCount = 0;
$("button").on("click", function() {
clickCount++;
$(".potatoe").attr("id", clickCount % 2 === 0 ? "bye" : "hello");
});
</script>
</body>
As you'll see everytime you click the button the CSS of the element will change
This is not exactly changing between CSS files but it ultimately changes the CSS of the elements you want to select.
You can implement by using JavaScript more easily:
const toggleButton = document.getElementById('button');
const workContainer = document.getElementById('work');
toggleButton.addEventListener('click', () => {
document.body.classList.toggle('blue');
toggleButton.classList.toggle('active');
workContainer.classList.toggle('blue');
if(document.body.classList.contains('blue')){
localStorage.setItem('blue', 'enabled');
}else{
localStorage.setItem('blue', 'disabled');
}
});
if(localStorage.getItem('blue') == 'enabled'){
document.body.classList.toggle('blue');
toggleButton.classList.toggle('active');
workContainer.classList.toggle('blue');
}

Can I use different styles within one div

I'm using a script to do a mouseover effect with images and also highlighting text in a different color using the getElementById phrase. I understand that an ID can only be used once, and if it needs to be used more than once I should use class. But there is no getElementByClass function. I have 2 areas of type that I want to highlight, one is centered, the other is left justified. Is there a way to use the same id for both styles?
<div id="georgia">
<style="text-align: center;">
<strong>Headquarters:
</strong>
</style>more text here
</div>
This is the script I am using:
<script type="text/javascript">// < ![CDATA[
function on(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="green";
};
};
function off(el) {
if (document.getElementById(el)) {
document.getElementById(el).style.color="";
};
};
// ]]></script>
So what you are saying is I can replace the getElementById with getElementByClassName then it will work?
This is the format I'm using, the first part of the text (Headquarters) is not showing up, but the second part (more text here) is fine.
You need to use document.getElementsByClassName, which returns a list of the objects with that class name:
var all = document.getElementsByClassName("bar");
for(var i = 0; i < all.length; i++){
var obj = all[i];
obj.style.fontWeight = 'bold';
}
<div id="foo" class="bar">hi</div>
<div class="bar">bye</div>
<div id="bar">sup</div>

HTML select in textarea always select white space after doubleclick

When I select string (word) by doubleclick in textarea, then always select word and white space after text.
Maybe it's trivial question, but how to select text by doubleclick without white space after word?
I have this solution see example below.
What is your opinion?
<html>
<body>
<textarea cols=50 ondblclick="checkDblClick(event)">abc1space abc2space abc3space abc
</textarea>
<script>
function checkDblClickDelayed(target) {
while (target.value.substr(target.selectionEnd -1, 1) == " ") {
target.selectionEnd = target.selectionEnd - 1;
}
}
function checkDblClick(e) {
//we make a delay of 0ms to wait until the selection is in the final position
target = e.target;
setTimeout(function()
{
checkDblClickDelayed(target);
}
, 0);
}
</script>
</body>
</html>
The answer is... you can't.
The closest you can get is double clicking the text, and then Shift+Clicking it.

Toggle between two div couples when you click on them

I've found some Javascript code on the web for toggling between two images when clicking on them as in this example.
Now I wonder how to achieve the same result using divs with the pictures being inside the divs.
Both the small and the large image will each be the background image of a div which is inside another div that forms the border (I need to do this to be able to set the inner border radius of the image, which I can when I use an inner div and set its border radius). So I have:
<div class="bordersmallpicture"><div class="smallpicture"></div></div>
and
<div class="borderlargepicture"><div class="largepicture"></div></div>
How can I tell Javascript to toggle between those two div couples instead of images? Here is the Javascript code that I found for the images:
<script>
var imageURL = "small-picture.png";
if (document.images) {
var smallpicture = new Image();
smallpicture.src = "small-picture.png";
var largepicture = new Image();
largepicture.src = "large-picture.png";
}
function changeImage() {
if (document.images) {
if (imageURL == "large-picture.png") {imageURL = "small-picture.png";}
else {imageURL = "large-picture.png";}
document.myimage.src = imageURL;
}
}
</script>
And the HTML part:
<img src="small-picture.png" name="myimage" title="Click to resize" alt="tree">
Can anyone give me a hint how to edit this code to toggle between the div couples mentioned above? Or will a whole new code be necessary when dealing with divs?
You simply need to toggle the classes. See a running example using your images as CSS background in the classes:
<div id="border-div" class="bordersmallpicture">
<div id="image-div" class="smallpicture"></div>
</div>
The the Javascript becomes:
<script>
function changeImage() {
var currentClass = document.getElementById('border-div').className;
if(currentClass == 'borderlargepicture') {
document.getElementById('border-div').className = 'bordersmallpicture';
document.getElementById('image-div').className = 'smallpicture';
} else {
document.getElementById('border-div').className = 'borderlargepicture';
document.getElementById('image-div').className = 'largepicture';
}
}
</script>
If you expect using javascript a lot, I recommend using jQuery which would make the code easier:
<script>
function changeImage() {
$('#border-div').toggleClass('bordersmallpicture').toggleClass('borderlargepicture');
$('#image-div').toggleClass('smallpicture').toggleClass('largepicture');
}
</script>
toggleClass turns ON/OFF a class (Here is the example)

Ideas for multicolored textbox?

In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.