user1391152 user1391152 - 3 months ago 8
Javascript Question

Check which element has been clicked with jQuery

I am trying to use an 'if' statement to determine which element was clicked.

Basically I am trying to code something along the lines of:

if (the element clicked is '#news_gallery li .over') {
var article = $('#news-article .news-article');
} else if (the element clicked is '#work_gallery li .over') {
var article = $('#work-article .work-article');
} else if (the element clicked is '#search-item li') {
var article = $('#search-item .search-article');
};


What is the proper jQuery syntax for this? Many thanks in advance.

Answer

Use this, I think I can get your idea.

Live demo: http://jsfiddle.net/oscarj24/h722g/1/

$('body').click(function(e) {

    var target = $(e.target), article;

    if(target.is('#news_gallery li .over')) {
       article = $('#news-article .news-article');
    } else if (target.is('#work_gallery li .over')) {
       article = $('#work-article .work-article');
    } else if (target.is('#search-item li')) {
       article = $('#search-item .search-article');
    }

});​
Comments