If i mouse over a TD element i want to highlight part of the string in another TD. Example: If i mouse over apple i want to highlight the apple part of applebanana.
I tried several things but didn't get closer to any solution. Thank you for your help.
My Code up to now: Cannot use word param because it is undefined. this.innerText does not return "apple".
Also onMouseout the hightlighted part of the string gets deleted.
function hightlightInput(word){
$(document.getElementById("testid")).html($(document.getElementById("testid")).html().replace(new RegExp("(apple)(?![^\">]*\"[^>]*>)", "i"), "<mark>$1</mark>"));
}
function resetHighlight() {
$(document.getElementById("testid")).find("mark").replaceWith(function() {
return $(document.getElementById("testid")).contents();
});
}
HTML
<table>
<tr>
<td onMouseOver="hightlightInput(this.innerText)"onMouseOut="resetHighlight()">apple</td>
<td id="testid">applebanana</td>
</tr>
</table>
In these situations, I always use a regexp and put the text in a <mark> element, which I remove later on.
You could then improve it by giving colors in and adding these as a style to the mark element, but by default it gives a yellow background to text (in most browsers). The mark element is easy to find back and usually doesn't get used for anything else, so its perfect for these things.
HTML:
<table>
<tr><td id="change">applebanana</td></tr>
<tr><td onMouseOver="highlightInput(this, this.textContent)"onMouseOut="resetHighlight(this)">apple</td></tr>
</table>
Here's a solution fully in native JS:
function highlightInput(element, word) {
element.innerHTML = element.innerHTML.replace(new RegExp("(" + word + ")(?![^\">]*\"[^>]*>)", "i"), "<mark>$1</mark>");
}
function resetHighlight(element) {
var marks = element.getElementsByTagName("mark");
var marksLength = marks.length;
for(var i = (marksLength - 1); i >= 0; --i)
{
element.replaceChild(document.createTextNode(marks[i].innerText), marks[i]);
}
}
Fiddle: http://jsfiddle.net/gpgekko/LshW6/1/
Here's a solution using the jQuery library:
function highlightInput(element, word) {
$(element).html($(element).html().replace(new RegExp("(" + word + ")(?![^\">]*\"[^>]*>)", "i"), "<mark>$1</mark>"));
}
function resetHighlight(element) {
$(element).find("mark").replaceWith(function() {
return $(this).contents();
});
}
Fiddle: http://jsfiddle.net/gpgekko/LshW6/
I'll leave the adaptation to find all elements to highlight up to you, let me know if you need help with that. But it's probably just looking through the table for occurrences of the word if I read your question correctly.
Related
This question already has answers here:
Highlight a word with jQuery
(13 answers)
Closed 5 years ago.
I'm trying to implement a search for a table, I found an answer on the web and I tried it out, it works fine!
now I want to highlight (change text colour: text colour class = blue-text) that search keyword found in a table cell, I searched for this answer but I didn't find anything helpful!
my HTML is
<table class="stdtable">
<tr>
<td id="stdname">Name</td>
<td id="stdreg">Reg. No.</td>
<td id="stdparent">Parent</td>
<td id="stdgrp">Group</td>
<td id="action">Action</td>
</tr>
</table>
and Jquery is
$("#filter").on("keyup", function() {
var searchKey = $(this).val().toLowerCase();
$(".stdtable tr #stdname").each( function() {
var searchStr = $(this).text().toLowerCase();
if (searchStr.indexOf(searchKey)!=-1) {
$(this).parent().show();
}
else {
$(this).parent().hide();
}
});
});
how can I highlight the searched text?
if I search N the text N in Name should change the colour
and if I clear the search field I need to clear colour of the text also
I don't know the setup you have, but I would make a class "highlighted"
and give this class the property: color: blue; or whatever any other css properties you want for the special results.
then
$("#stdname").addClass("highlighted");
and
$("#stdname").removeClass("highlighted");
when you remove the search field
Edit: Leaving the above for someone that wants all the text.
You could take
var s = $(this).val();
var txt = $("#stdname").val().replace(s, '<span style="color: blue">' + s + '</span>');
$("#stdname").val(txt);
please note, you are going to end up with strange behavior if you don't strip the span statement from $("#stdname").val() every time a key is up
This question builds on an answer provided in How to wrap word into span on user click in javascript.
In my example, the user can double-click on any word to wrap it in a span element, but b/c this is based on splitting on whitespace, it won't work if the word is followed by punctuation.
HTML:
<div class="color-coding">
<span class="orange color-coding">Hello world this is some text.</span>
<br>
<span class="orange color-coding">Here is some more!</span>
</div>
JS:
jQuery(document).ready(function($) {
$('.color-coding').dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var sword = $.trim(range.toString());
if(sword.length)
{
var newWord = "<span class='highlight'>"+sword+"</span>";
$(this).each(function(){
$(this).html(function( _, html ) {
return html.split(/\s+/).map(function( word ) {
return word === sword ? newWord : word;
}).join(' ');
});
});
}
range.collapse();
e.stopPropagation();
});
});
I could add punctuation detection for the split, but that would of course remove the punctuation, and I need to retain it, so using the following won't meet my needs:
html.split(/\s+|[.,-\/#!$%\^&\*;:{}=\-_`~()]/)
Fiddle: http://jsfiddle.net/b11nxk92/3/
execCommand
Perfect solution for evergreen browsers:
if(sword.length) {
this.setAttribute('contenteditable','true');
document.execCommand("insertHTML", false, "<span class='highlight'>"+sword+"</span>");
this.removeAttribute('contenteditable');
}
This solution, toggles the container to editable mode, then trigger a command to insert the new html code. See: https://msdn.microsoft.com/en-us/library/hh801231(v=vs.85).aspx#inserthtml and https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
Fiddle: http://jsfiddle.net/b11nxk92/6/
RegExp
Also, I love RegExp so I made this solution.
if (sword.length) {
$(this).each(function(){
$(this).html(function( _, html ) {
return html.replace(
new RegExp("([^\\w]|^)("+sword+")([^\\w]|$)","g"),
"$1<span class='highlight'>$2</span>$3"
);
});
});
}
Instead of using split and then join the regular expression selects three elements (a non word character or the begining) + (our word) + (a non word character or the end) then using $ you choose where to keep it.
Fiddle: http://jsfiddle.net/b11nxk92/4/
jqTds =[
<td class="hidden-xs sorting_1">text1</td>
<td class=" ">text2</td>
<td class=" ">text3</td>
<td class=" ">text4</td>
<td class=" ">Edit</td>
<td class=" ">Delete</td>]
How can I get all elements that has a "anchor" with class "edit-row" or "delete-row" and get all other that does not have it
// I am editing a script that uses DataTables.Js what I am trying to do is getting all elements from a table row into (var jqTds = $('>td:not(.hide_me)', nRow)) and now I want to include an input in all elements except the ones that has save-row class and edit-row class cos they are link to save/delete
thanks in advance
No idea why you have them in "an array", but if you run this while they are still in the DOM, use the :has pseudo selector:
var $tds = $('td:has(a:.edit-row,a:delete-row)');
var $otherTds = $('td').not($tds);
The first one reads. *find any td that has an anchor within it with class edit-row or an anchor within it with class delete-row".
The second one simply says, find all tds and exclude the first lot from the matches :)
You can use $.grep() to filter your array.
Using the function passed to $.grep() you can try and find your elements within the current <td>. If neither a.edit-row or a.delete-row are found return true, otherwise return false:
var filteredTds = $.grep(jqTds, function(td){
var $td = $(td);
return !$td.find('a.edit-row').length && !$td.find('a.delete-row').length;
});
JSFiddle
I was able to do like this:
for (var i = 0; i < editColumn.length; i++) {
if ($(editColumn[i]).find("a").hasClass("edit-row") == true) {
editColumn[i].innerHTML = '<a class="save-row" href="">Salvar</a>';
}
else if ($(editColumn[i]).find("a").hasClass("delete-row") == true) {
editColumn[i].innerHTML = '<a class="cancel-row" href="">cancelar</a>';
}
I want to add a class (and later on to send that string to php) to a text with javascript. Whenever I try to do that, the code is adding the class to the first occurrence of my selection, not to the actual selection. Keep in mind that I want to send that EXACT selection to php (and put it in a database as well so it keep that class even after refresh).
JQ
$("#highlight").click(function(){
paraval = $('#para').html();
sel = window.getSelection();
newst = '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(sel, newst);
$('#para').html(newvalue);
});
HTML
<p>Will only highlight if text is selected from comment class div only</p>
<div class="comment" id="para" contenteditable="true">Here goes some text Here goes some text Here goes some text Here goes some text
Some other text</div>
<input type="button" value="Highlight" id="highlight"/>
CSS
.selectedText{
background-color:yellow;
}
.comment{
border: solid 2px;
}
.comment::selection {
background-color: yellow;
}
example here: http://jsfiddle.net/zq1dqu3o/3/
try to select the last occurrence of the word "text". the first one will get the class "selectedText"...
thanks
Call me lazy, but if you don't mind span being you selection marker tag, you can use rangy's cssApplier class.
var cssApplier;
$(document).ready(function() {
rangy.init();
cssApplier = rangy.createCssClassApplier(
"selectedText", {normalize: true,
applyToEditableOnly:true});
});
$("#highlight").click(function(){
if(cssApplier != undefined)
{
cssApplier.toggleSelection();
}
});
I use applyToEditableOnly here to make it only work in that specific div. (I'm not sure how cross-browser compatible that particular setting is. Worked in Chrome and Firefox though.) This uses position rather than selection text to decide what to mark.
JS Fiddle Here: http://jsfiddle.net/zq1dqu3o/7/
You can get the last occurence with lastIndexOf() and proceed like this:
$("#highlight").click(function(){
paraval = $('#para').text();
sel = "text";
var n = paraval.lastIndexOf(sel);
var before = paraval.substring(0,n);
newst = before + '<a class="selectedText">' + sel + '</a>';
newvalue = paraval.replace(paraval, newst);
$('#para').html(newvalue);
});
Just created a fiddle for it: Replacing last occurence
Note: This quick example is only working because the word you want to highlight is at the last position of the text, but you can check out if this solution is ok for your request. In case the last occurence of the word is elsewhere, just create a variable "after" that contains the text following the last occurence of the word to the end.
Have just provided an example for this in updated fiddle: Replacing last occurence update
with following update to previous code:
var after = paraval.substring(n + sel.length, paraval.length);
newst = before + '<a class="selectedText">' + sel + '</a>' + after;
I'm trying to select an element from my HTML code, to then use it in JavaScript (it needs to be highlighted). The HTML consists of a table with 36 td's.
My code so far:
var box;
function getRandom()
{
return (Math.floor(Math.random()*37))
}
function highlight()
{
box = document.getElementById(getRandom());
box.style.backgroundColor = "yellow";
}
If anyone can give me any pointers, it'd be appreciated. I know it would be easy using jQuery, but I haven't begun learning that yet.
Edit: excerpt of the HTML code, this goes up to name="36".
<table id="reflexTable">
<tbody>
<tr>
<td name="1"></td>
<td name="2"></td>
<td name="3"></td>
<td name="4"></td>
<td name="5"></td>
<td name="6"></td>
</tr>
A nicer way that does not involve setting element ids:
function highlight() {
// get all TDs that are descendants of table#reflexTable:
var tds = document.getElementById('reflexTable').getElementsByTagName('td');
// get a random int between 0 (inclusive) and tds.length (exclusive)
var rand = Math.floor( Math.random() * tds.length );
// highlight td at that index
tds[rand].style.backgroundColor = "yellow";
}
The big advantage of this method is that you can add/remove as many TDs as you please without needing to edit your JS to generate a valid random number.
getElementById gets the element which has the matching id. Your table data cells don't have an id at all. They have a name, but HTML doesn't allow that.
Switch to id.
HTML 4 doesn't allow an id to start with a number. Prefix the id with a common string. Then:
document.getElementById("foo" + getRandom());
You're not setting the id attribute, you're setting the name attribute, change it to:
<td id="1"></td>
...etc
Several things:
You should declare the box variable inside the highlight function.
You have to convert that random number to a string.
Quentin mentioned something important--you should give each table element an id of something like "s0","s1","s2", etc...
Start the naming at 0 because your getRandom function will sometimes return it.
function highlight(){
var number;
number = getRandom().toString();
var box;
box = document.getElementById("s" + number);
box.style.backgroundColor = "yellow";
}