1

This is the table that should display my search result:

<table id="searchbarresults">

</table>

This is my javascript:

 jQuery(document).ready(function(){
jQuery("#searchresults").keyup(function(){

 for(i=0;i<searchbarresultarray.length;i++){

           htmloutput= htmloutput+"<tr><td class='searchbarresult' id='"+i+"'>"result"</td></tr>";

            }
    jQuery("#searchresults").html(htmloutput);

});

jQuery(".searchbarresult").mouseover(function(){
      jQuery(this).css( "background-color", "black" ); 
    });
});

This outputs a list with table rows. All with class 'searchbarresult' and a unique id. But it does not work. Is it because the table rows are created after the mouseover event is hooked? And how can i go around this?

JeffreyR
  • 591
  • 2
  • 9
  • 22

2 Answers2

3

try

jQuery(document).on('mouseover','.searchbarresult',function(){
    jQuery(this).css( "background-color", "black" ); 
});
Inus Saha
  • 1,918
  • 11
  • 17
  • Can you explain to me why this works and the other does not? I use my version all the time with code that is not dynamically generated. – JeffreyR Feb 18 '18 at 09:21
  • your one does not work because the element gets added after the event handler is added. this way it will work even if element is added after the event handler is attached. – Inus Saha Feb 18 '18 at 09:24
1

To make table row clickable add onclick="window.location='#';" to the tr element as follows:

 jQuery(document).ready(function(){
    jQuery("#searchresults").keyup(function(){

     for(i=0;i<searchbarresultarray.length;i++){

               htmloutput= htmloutput+"<tr onclick="window.location='#';"><td class='searchbarresult' id='"+i+"'>"result"</td></tr>";

                }
        jQuery("#searchresults").html(htmloutput);

    });

    jQuery(document).on('mouseover','.searchbarresult',function(){
        jQuery(this).css( "background-color", "black" ); 
     });
    });
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114