Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:
Having multiple selectors like
$('a.button, span.xyz, a.another').click(function(e) {
var clicked_element = ???;
});
, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)...
.
Thanks.
Using $(this) will get you the element that was clicked.. and using is() can help you determine what was clicked.
$('a.button, span.xyz, a.another').click(function(e) {
if ($(this).is("a.button")) {
alert("a.button was clicked");
} else if ($(this).is("span.xyz")) {
alert("span.xyz was clicked");
} else if($(this).is("a.another")) {
alert("a.another was clicked);
}
});
Edited:
As I wrote up this answer it seems there is a better approach. Patrick DW's comment intrigued me and I wanted to know more. His clarification is here jQuery - Issues with combining selectors in a single event handler
This would be a better approach
$("a.button").click(function (e) { ... });
$("span.xyz").click(function (e) { ... });
$("a.another").click(function (e) { ... });
As I understand it if your goal was to place common functionality in one spot then this is how it should be handled
function commonFunctionality(elementSelector) {
// common code for all elements here or at the end
switch (elementSelector) {
case "a.button":
//do stuff for a.button only;
break;
case "span.xyz":
//do stuff for span.xyz only;
break;
case "a.another":
//do stuff for a.another only;
break;
}
// common code for all elements
}
$("a.button").click(function (e) { ... });
$("span.xyz").click(function (e) { ... });
$("a.another").click(function (e) { ... });
The element which triggers an event is available within the function as $(this)
, i.e.
$('a.button, span.xyz, a.another').click(function(e) {
var clicked_element = $(this);
});
You can also test to identify if the element matches a particular selector using is():
if ($(this).is('a.button'))) { ... }
I would agree with Patrick and Dexter about separating these elements if they have different functionality. But if you are going to use this method, try using some of the built in javascript methods. I don't know what the HTML markup looks like, but assuming this markup, you can try the script below:
<a class="button" href="http://somesite.com">Some Site</a>
<span class="xyz">span</span>
<a class="another" href="/topics/topic2.html">Topic 2</a>
$('a.button, span.xyz, a.another').click(function(e) {
var clicked = 'a.another';
if (this.tagName == "SPAN") { clicked = 'span.xyz'; }
if (this.href.match('somesite')) { clicked = 'a.button'; }
// Do something
});