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.
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.
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'.
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 } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With