Botić Denis Botić Denis - 6 months ago 21
jQuery Question

JS - if I first run search (highlight text) then .click on section doesn't wanna work

If I run search and highlight text:

$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
highlightSearch();
}
});

function highlightSearch() {

$('span').removeClass('highlighted');
var text = document.getElementById("query").value;
var query = new RegExp("(\\b" + text + "\\b(?!([^<]+)?>))", "gim");
var e = document.getElementById("searchText").innerHTML;
var enew = e.replace(/(<span class='highlighted'>|<\/span>)/igm, "");
document.getElementById("searchText").innerHTML = enew;
var newe = enew.replace(query, "<span class='highlighted'>$1</span>");
document.getElementById("searchText").innerHTML = newe;

}


then this part of code stop working:

$('.service-box').click(function(){
$('#siteOverlay').addClass('overlay-active');
$('#popupWindow').addClass('service-active');
$('#popupWindow #contentBox').html($(this).html());
});


It doesn't register .click() anymore. I can not find out what is wrong. Can You please help me resolve this?

Thanks!

Answer

You are using innerHTML and getting rid of all the event handlers. If you are going to use it, please delegate the events:

$(document).on("click", '.service-box', function(){                    
  $('#siteOverlay').addClass('overlay-active');
  $('#popupWindow').addClass('service-active');
  $('#popupWindow #contentBox').html($(this).html());
});

Since I don't know what's the static parent, I have used document. Please replace it with a selector for a static parent instead.