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?

1

2 Answers 2

3

try

jQuery(document).on('mouseover','.searchbarresult',function(){
    jQuery(this).css( "background-color", "black" ); 
});
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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" ); 
     });
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.