I am using the following code to highlight series of words in a paragraph. They are all highlighted as intended. The for loop enables to pick up each word and highlights them. I want highlighting to take place in different colours in an order. For example: yellow, blue, green and cyan etc. are to be used to highlight.
I tried to include different css definitions and call through for loop. Also I tried to name different colour within the loop. All these failed.
I am using following js function to highlight text:
var str = "the leading blade edges of the fan blade is bulged";
for (var i = 0; i < obj.result.length; i++) {
var start = obj.result[i].startPos,
end = obj.result[i].endPos,
before = str.substring(0, start),
after = str.substring(end),
middle = "<mark>" + obj.result[i].name + "</mark>";
str = before + middle + after;
}
document.getElementById("result").innerHTML = str;
}
At present highlight takes place on series of words using 'mark' as defined in css:
mark {
padding: 0;
background-color:yellow;
}
Here is the full working JFiddle
function myFunction() {
var str = "the leading blade edges of the fan blade is bulged";
var colors = ['red', 'blue', 'green', 'cyan'],
i = 0;
var obj = {
"result": [{
"name": "blade",
"startPos": 12,
"endPos": 17
}, {
"name": "bulged",
"startPos": 44,
"endPos": 50
}]
};
obj.result.sort(function(a, b) {
return b.startPos - a.startPos;
})
for (var i = 0; i < obj.result.length; i++) {
var start = obj.result[i].startPos,
end = obj.result[i].endPos,
before = str.substring(0, start),
after = str.substring(end),
middle = "<mark>" + obj.result[i].name + "</mark>";
str = before + middle + after;
}
document.getElementById("result").innerHTML = str;
}
mark {
padding: 0;
background-color: yellow;
}
mark2 {
padding: 0;
background-color: blue;
}
<body onload="myFunction()">
<span id="result">the leading blade edges of the fan blade is bulged</span>
</body>
The expected output is highlight colours should change in order as defined. Instead I get only yellow consistently.
mark
element and use that in css to define the different colors. – Federico klez Culloca