user3654920
user3654920

Reputation:

Jquery - Target 1 div with .click()

This might be a beginners question, but I'm at a loss.

My objective is to have a button that when pressed the class that the button was in does something... if that makes sense.. Here is my code for my content on the page:

if(domain == 'google.com') {
$('#content').append('<div id="highlight"><h1 id="headline">'+title+'</h1><img id="dropDown" src="images/small-dropdown.png" alt=""/><img class="card" src="'+URL+'"/></div></br>');
$('.card').hide();     
}

So that code loops about 25 times and then in my content div I have a nice list of the sites I want. My next piece of code is:

$("#dropDown").click(function() {
    $('.card').toggle();
});

The problem I am having is that when I press on the dropDown button the image card is supposed to appear for only 1 div, instead, images are showing up for each div, and I just want to target the div that the button was in. How would I do that?

Upvotes: 3

Views: 110

Answers (3)

Chris Lam
Chris Lam

Reputation: 3614

In order to bind event to dynamically generated elements, you should use .on():

http://api.jquery.com/on/

It also works for non-generated elements.

Upvotes: 0

Jan Pfeifer
Jan Pfeifer

Reputation: 2861

It is bad thing to have more than one element with the same id, but you can use something like this:

$("#dropDown").click(function() {
   $(this).find('.card').toggle();
});

Upvotes: -1

Satpal
Satpal

Reputation: 133403

Use

$('#content').on('click', "#dropDown", function() {
    $(this).next('.card').toggle(); //Use next()
});

As you are generating elements dynamically. You should use Event Delegation using .on() delegated-events approach.

Also Important: IDs must be unique, So I would suggest you to use class selector like

To generate element use

if(domain == 'google.com') {
$('#content').append('<div id="highlight"><h1 id="headline">'
 + title +'</h1><img class="dropDown" src="images/small-dropdown.png" alt=""/><img class="card" src="'+URL+'"/></div></br>');
$('.card').hide();     
}

Event Binding

$('#content').on('click', ".dropDown", function() {
    $(this).next('.card').toggle(); //Use next()
});

Upvotes: 2

Related Questions