0

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?

5
  • Your posted code is part of content loaded through ajax or is part of main page? What about posting your code/logic regarding how do you load content using ajax?! Commented Jan 20, 2016 at 9:27
  • Its loaded on the main page, you can see the code in full here: view-source:ifyouneedafriendgetadog.com/jobs (dev url) Commented Jan 20, 2016 at 9:29
  • Delegate events for dynamic elements. Now because your code not just only bind events, you should set it in a function and call it (again?) once your ajax has finish. There are thousand already dupes regarding this, if i'm correct... FYI, this is quite inconsistent to check for $(window).width(), use instead: window.matchMedia() Commented Jan 20, 2016 at 9:32
  • Ok that makes sense, I will give that a try Commented Jan 20, 2016 at 9:33
  • That seems to have resolved it thanks! Commented Jan 20, 2016 at 9:38

1 Answer 1

1

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 }) 
Sign up to request clarification or add additional context in comments.

4 Comments

But img isn't child of .check, it is inserted after. If you want to be sure delegation would work (if event bubbles to that level), delegate it to document level
@A.Wolff Thanks.Its my mistake.But i think rather than document immediate parent is much better
Ok, i give you credit for this answer even it is really complete, if OP set it in a loop as in his posted code, you will bound delegate event at each iteration of this loop. But at least, you gave the correct way to delegate event :)
@A.Wolff :) yes there is loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.