1

I have the following code just to display some results and change the background of the <div> to yellow on hover. It works fine on all records (or loops) excluding the last one. Any hint?

function tryit(){
  $(document).ready(function(){
    var url="api2.php";
    $.getJSON(url,function(json){
      $.each(json,function(i,dat){

        $(document).ready(function(){
          $(".products").hover(function(){
            $(this).css("background-color", "yellow");
          }, function(){
            $(this).css("background-color", "white");
          });
        }); 

        $("#data").append(
          '<div class="products">'+
          '<h1>Product: '+dat.product+'</h1>'+
          '<p>Seller : <em>'+dat.name+'</em>'+
          '<p>Email : <em>'+dat.email+'</em></p>'+
          ''+
          '<p>Phone: : <em>'+dat.phone+'</em></p>'+
          '<p>Category : <em>'+dat.category+'</em></p>'+
          '<p>Cost : <em>'+dat.cost+'</em></p>'+
          '<p>Description : <em>'+dat.description+'</em></p>'+
          '<p>Date : <em>'+dat.date+'</em>'+

          '<hr>'+
          '</div>'


        );
      });
    });
  });
}
Wing
  • 8,438
  • 4
  • 37
  • 46
Arihant
  • 3,847
  • 16
  • 55
  • 86

3 Answers3

3

The code does not work because when you attempt to bind the hover event to elements with the products class, these elements do not exist in the DOM yet as you call append after that.

As another answer has suggested you can bind the hover event after calling append.

An alternative is to use the on event handler function. Here is the documentation for that from jQuery: http://api.jquery.com/on/. With the on function you can use delegated events which will allow you to attach events on dynamically added elements.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

Some example code:

$(document).on('hover', '.products', function() {
   // do your thing
});

When using the on method, you can move it out of the loop as you do not need to keep attaching the hover event multiple times.

A Stack Overflow thread discussing the differences between on and click methods is also a useful read: Difference between .on('click') vs .click()

Community
  • 1
  • 1
Wing
  • 8,438
  • 4
  • 37
  • 46
1

You should set the ".hover()" be after the ".append()" method

$("#data").append('...');

$(".products").hover(function(){
  $(this).css("background-color", "yellow");
}, function(){
  $(this).css("background-color", "white");
});
0

You're adding .products handler before adding the element. Element added in previous loop will use the handler. Last one added does not.

change

$(".products").hover(function(){

to

$(document).on("hover", ".products", function(){

Also you can take the handler code out of the loop.

yezzz
  • 2,990
  • 1
  • 10
  • 19