Webbly Brown
Webbly Brown

Reputation: 1002

jQuery does not load on Ajax

Im currently trying to do some work on some code I did not write or fully understand. The page dynamically calls in content with AJAX. I am trying to manipulate that content but of course because the page has already been loaded when I apply it to the dynamic content it gets ignored. Here are some basic examples of the jQuery i'm trying to call:

$(".check").each(function() {
    $(this).hide();
    var $image = $("<img src='img/checked.png' />").insertAfter(this);
    $image.click(function() {
        var $checkbox = $(this).prev(".check");
        $checkbox.prop('checked', !$checkbox.prop('checked'));

        if ($checkbox.prop("checked")) {
            $image.attr("src", "img/checked.png");
        } else {
            $image.attr("src", "img/unchecked.png");
        }
    })
});

if ($(window).width() < 500) {
    $('.panel-collapse').removeClass('in');
} else {
    $('.panel-collapse').addClass('in');
}

How can I get this to work with ajax please?

Upvotes: 0

Views: 49

Answers (1)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Use it in this way.

$image.on('click',function() {
        // your script 
})

As you adding content dynamically it need event delegation.

UPDATE :

 $("some_parent_id_or_class").on('click','img_with_some_class_or_id',function(){

    //your script
 })

e.g.

 $("some_parent_id_or_class").on('click','img',function(){

    //your script
 })

Upvotes: 1

Related Questions