0

I have a page where the contents displayed from database using jquery and ajax. There are lot of processes in the page like Adding new content and image, Editing, Deletion etc and all are using ajax. But now some of event functions like click , mouseenter are not working in the content which where displayed from the database.

for example: This is how i display images in the page

for(var i=0;i<images.length;i++)
{
$("#content").append("<img src='"+images[i]+"' class='img'  width='300' height='200' />");
}

Images are displayed properly. but when trying to do somthing on click event in images like this, its not working

 $("#content .img").on('click',function()
  {
  //here comes my process, but its not working
   }

Please help me to solve this problem.

7
  • what is the version of your jquery? Commented Oct 4, 2013 at 6:38
  • i think you forgotten closing brace in click function ); Commented Oct 4, 2013 at 6:38
  • if you're using an old version of jquery instead using .on() try using .live() for delegation Commented Oct 4, 2013 at 6:39
  • Are you writing these events in AJAX success ?? Commented Oct 4, 2013 at 6:52
  • what is not working? not triggering or produce errors? Commented Oct 4, 2013 at 6:59

3 Answers 3

3

Try:

$("#content").on("click", ".img", function() {

});

The problem is that $("#content img") creates a jQuery collection of elements that exist at the time it is run. When you start dynamically adding new elements, they don't have the event listener applied to them automatically.

What $("#content").on("click", ".img") does is provide for event delegation. So what's really happening is an event listener that is applied to $("#content") but only fired when that event comes from a descendant with a matching selector (.img in this case).

More info at http://api.jquery.com/on/.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please tell me what to do in case of hiding the image like $(".img").hide();
@user2765968 I'm afraid I don't understand your question. If you hide images, they won't fire a click event because there won't be anything to click.
0

Try like this

$(document).on('click', '#content .img',function()
{
  ...
});

Comments

0

This problem will always arise when you are trying to add some dynamic content. So,to resolve this always keep in mind some point.

  • All use some static element to reference the dynamic you are trying to apply event on. Example : in your case try using

    $("#content").on('click', 'img', function(){ //try using this way make your code works fine.! });

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.