Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


How to click on a div retrieved from a php file using JQuery

I am creating a autocomplete box so I want when the data get's retrieved from the php file to the page I sent the ajax request but when I add the click event to the page I sent the request it doesn't work.

2 Answers

Hi Dustin,

Can you show the relevant code?

So you're sending an ajax request to a php script and then a div is being dynamically added to your page and you want to be able to have a 'click' event for it?

All I can suggest at this point is that you probably need to use event delegation with the .on method. http://api.jquery.com/on/

A general example:

$( "#div-parent" ).on( "click", "div", function() {
  // Whatever you need to do

The "div" selector in the second argument would be whatever selector you need to uniquely target the div that's retrieved from the php page.

"#div-parent" is whatever selector you can use for a parent element to that div that already exists on the page when that code is run. The click handler will be attached to that parent element but the div retrieved from php will be able to receive the clicks.

Thanks a lot man

Kevin Korte
Kevin Korte
28,148 Points

If I'm understanding correctly, you're trying to attach a click event to a div that gets returned to the page via Ajax? The click event likely isn't working because at the time the jQuery runs, the div doesn't actually exist.

You'll need to refactor your click event to use what is usually know as "event delegation". Here is the jQuery link http://learn.jquery.com/events/event-delegation/

Your new click event might look like

$( ".class-selector" ).on( "click", "div.div-class", function() {
    //What to do on this new click event

The .class-selector needs to be some sort of valid selector for an element that is going to be there when the DOM loads. You may need to go up the DOM tree all the way to the body selector if necessary. The more specific you can get here thought, the slightly better performance you should have. Next we're basically saying "on a click event" we want to look for this next selector. In this example I used the selector ".div-class" but it should be whatever selector you need it to be. And than finally your click function, with what you are trying to actually do.

That should solve your problem. Let us know how it goes.

Thank you very much for trying to help me