I’m trying to do a specific action on the clicked element if an argument is passed in the on click method in jQuery. When I try to access this
it’s referencing the entire window instead of the clicked on element. How would I access the clicked on element in the handler?
Here’s the code I’m using:
var myfunction = function(action) {
var content;
var $this = $(this);
if(action === "one") {
$(".output").text("clicked on one");
$this.addClass("one");
}
if(action === "two") {
$(".output").text("clicked on two");
$this.addClass("two");
}
};
$("#button").on("click", function(event) {
myfunction("one");
});
$("#button2").on("click", function(event) {
myfunction("two");
});
I set up an example on jsbin here. Any help would be appreciated.
Advertisement
Answer
There are several ways to do this.
JQUERY WAY:
Within your jquery click event handlers you have the event
object. It has a property called target
which is what you’re looking for.
Change this: $this.addClass("one");
To this: $(event.target).addClass("one");
You can also do this: event.target.className = "one"
And do for “two” as well obviously…
VANILLA WAY:
You can just pass in an extra argument representing your clicked element.
var myfunction = function(action, element) {
var content;
if(action === "one") {
$(".output").text("clicked on one");
$(element).addClass("one");
// or event.target.className = "one"
}
if(action === "two") {
$(".output").text("clicked on two");
$(element).addClass("two");
// or event.target.className = "two"
}
};
$("#button").on("click", function(event) {
myfunction("one", this);
});
$("#button2").on("click", function(event) {
myfunction("two", this);
});