Class selectors on javascript generated content

It was a posting question, George's link to the previous question answered

I have a problem where selectors don't work with dynamically generated javascript content.

The original work is just fine. When the for loop generates more divs, even though they got the same class, the css "hover" style will not be applied.

The code that generates divs:

    for (x; x < y; x++) {
        output = output + '<div class="over">'+
            'But not for these generated divs'+ 
            '</div>';
    }
   $("#content").html(output);

      

Code that styles divs with class "over":

$(".over").hover(function () {
    $(this).addClass("styling");
});


$(".over").mouseout(function () {
    $(this).removeClass("styling");
});

      

http://jsfiddle.net/kjhansen/1e08ypms/28/

+3


source to share


1 answer


Use jQuery on()

Try this:

$(document).on('mouseover','.over',function () {
    $(this).addClass("styling");
});


$(document).on('mouseout','.over',function () {
    $(this).removeClass("styling");
});

      



EXAMPLE FIDDLE

0


source







All Articles