Shniper
Shniper

Reputation: 854

Checking Id of clicked element

I have several images with the same class and would like to set up a click function that changes the text in some elements based on which image is clicked. My if statement is not working, I'm not entirely sure why because I've used this method before, or so I thought.

$('.gallery_image').click(function(e) {
    var t = $(this);
    if(t.id == 'csf') {
        console.log('It works!');
    }
});

JSFIDDLE

Upvotes: 3

Views: 59

Answers (2)

Steven Guggenheimer
Steven Guggenheimer

Reputation: 26

An alternate solution is using classes instead of id's. Call the click function on the class they share then use a second class to distinguish them with the hasClass function:

 <div id="csf" class="gallery_image csf">csf</div>
<div id="csi" class="gallery_image csi">csi</div>

    $('.gallery_image').click(function(e) {
    var t = $(this);
    if(t.hasClass('csf')) {
        alert("It works!");
    }

     else if(t.hasClass('csi')) {
        alert("So does this!");
    }
});

Upvotes: 0

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

Use t.attr('id') instead of t.id

More about .attr()

Upvotes: 6

Related Questions