Reputation: 2144
I want to highlight the text in div by javascript function which takes the startindex and endindex as arguments.
NOTE : Everytime i call the function the previous highlight must be cleared.
I somehow made this
HTML CODE
<div id="readPara">Sounds good, eh? So good that the ASP.NET team decided to incorporate the provider model for authentication (membership), roles, user profile, session and other aspects of the runtime into the ASP.NET 2.0 release in 2005. To capitalize on the provider model several new controls were added such as the CreateUserWizard, Login, ResetPassword and ChangePassword controls. These controls, given the provider model, could implement these features without knowing the details of the database being used.</div>
JavaScript Code
function highlightWord(start,end){
$('.highLight').removeClass();
var line = $('#readPara').text();
console.log(line);
if(end>line.length){
end = line.length;
}
var newLine = line.substring(0,start) + "<span class='highLight'>" + line.substring(start,end) + "</span>" + line.substring(end,line.length);
console.length(newLine);
$('#readPara').contents().replaceWith(newLine);
}
Try to help me.
Upvotes: 0
Views: 164
Reputation: 28523
Try this : you don't need to remove highLight
span as you are replacing all contents again. And replace html, that will take span as a html element.
function highlightWord(start,end){
var line = $('#readPara').text();
console.log(line);
if(end>line.length){
end = line.length;
}
var newLine = line.substring(0,start) + "<span class='highLight'>" +
line.substring(start,end) + "</span>"
+ line.substring(end,line.length);
console.log(newLine);
$('#readPara').html(newLine);// replace newline here
}
Upvotes: 2
Reputation: 1199
Try this Fiddle
New line should be like this-
var newLine = line.substring(0,start) + "<span class='highLight'>" +
line.substring(start,end) + "</span>"
+ line.substring(end,line.length);
Upvotes: 0