Reputation: 11
I want create an effect of highlighting to read a text. For example i want highlight this text:
<div>
<p>Lorem Ipsum <i>is simply dummy</i> text of the printing and typesetting industry</p>
<p>Lorem Ipsum is simply dummy text of <u><b>the printing and</b></u> typesetting industry</p>
<p>Lorem Ipsum is <b>simply dummy</b> text of the printing and typesetting industry</p>
</div>
For the moment I found this function but it does not preserve the tags:
var text = $('div').text();
var regex = text.split(' ');
$('div').html('');
for (i = 0, len = regex.length; i < len; i++) {
$('div').append('<span>' + regex[i] + ' </span>');
}
$('#click').click(function() {
j = 0;
var t = setInterval(
function() {
$('span').eq(j).addClass('highlight');
j++;
}, 500
);
});
I think is possible with regular expression for example: /(<[^>]+>)?([^<]*)/g
To capture the tags and put them in a table to read this table after but I do not know how do this. For the moment my result can be seen here: jsfiddle
My while loop won't stop. So stop the script. Thanks!
I found what I wanted : jsfiddle
var pattern = /(<[^>]+>)?([^<]*)?/g
var text = $('div').html();
array = new Array();
while ((result = pattern.exec(text)) && (result[0].length) > 0) {
array.push(result[1]);
if (typeof result[2] !== 'undefined' && result[2].trim().length > 0) {
var textSplit = result[2].split(' ');
for (i = 0, len = textSplit.length; i < len; i++) {
if (textSplit[i].length > 0) {
array.push('<span>' + textSplit[i] + '</span>')
}
}
}
var i = 0;
};
var x = document.getElementById("demo");
x.innerHTML = array.join(" ");
$('#click').click(function () {
j = 0;
var t = setInterval(
function () {
$('span').removeClass('highlight');
$('span').eq(j).addClass('highlight');
j++;
if (j >= $('span').length) {
clearInterval(t);
}
}, 500);
});
thank you for your help Nelson
Upvotes: 0
Views: 314
Reputation: 50643
Cancel the interval when it reaches the total number of span , like this:
var t = setInterval(
function() {
$('span').eq(j).addClass('highlight');
j++;
if (j >= $('span').length ) {
clearInterval(t);
}
}, 500
);
See working fiddle
Upvotes: 1