Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 903
user1391152 Avatar asked May 22 '12 17:05

user1391152


People also ask

How do I know which element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

Is jQuery a selector?

The is( selector ) method checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. If no element fits, or the selector is not valid, then the response will be 'false'.


2 Answers

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');     }      if (article) {        // Do Something     } });​ 
like image 146
Oscar Jara Avatar answered Sep 22 '22 12:09

Oscar Jara


So you are doing this a bit backwards. Typically you'd do something like this:

​<div class='article'>   Article 1 </div> <div class='article'>   Article 2 </div> <div class='article'>   Article 3 </div>​ 

And then in your jQuery:

$('.article').click(function(){     article = $(this).text(); //$(this) is what you clicked!     });​ 

When I see things like #search-item .search-article, #search-item .search-article, and #search-item .search-article I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.

like image 37
vpiTriumph Avatar answered Sep 20 '22 12:09

vpiTriumph