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 el
Another option can be to utilize the tagName
property of the e.target
. It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV
or an A
tag, and I want to see if that class was clicked, and determine whether it was the DIV
or the A
that was clicked. I can do something like:
$('.example-class').click(function(e){
if ((e.target.tagName.toLowerCase()) == 'a') {
console.log('You clicked an A element.');
} else { // DIV, we assume in this example
console.log('You clicked a DIV element.');
}
});
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
}
});
Answer from vpiTriumph lays out the details nicely.
Here's a small handy variation for when there are unique element ids for the data set you want to access:
$('.news-article').click(function(event){
var id = event.target.id;
console.log('id = ' + id);
});
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.
The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:
http://api.jquery.com/category/selectors/
However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.
$("#news_gallery li .over").click(function() {
article = $("#news-article .news-article");
});