Kyle Yeo
Kyle Yeo

Reputation: 2368

How do I take in a event variable in Javascript / jQuery?

This feels like a amateurish question, but how do you take in an event in a custom function in Javascript / jQuery?

Right now I'm using this:

$(".button").on("click", function(event){
    removeButton();
});

function removeButton() {
    $(this).removeClass("specifiedClass");
}

I'm trying to make removeButton() understand that I want it to remove the class that is on the .button itself.

I'm not sure how to make removeButton() take in the event, but I've tried:

$(".button").on("click", function(event){
    removeButton(event);
});

function removeButton(event) {
    $(this).removeClass("specifiedClass");
}

But its not working. Does anyone know how?

Upvotes: 0

Views: 972

Answers (2)

Kevin Ji
Kevin Ji

Reputation: 10489

SLaks' solution is perfectly acceptable, but if you didn't want to change your removeButton function, you could use call or apply to invoke your function with the proper this value:

$(".button").on("click", function(event){
    removeButton.call(this);
});

function removeButton() {
    $(this).removeClass("specifiedClass");
}

Upvotes: 1

SLaks
SLaks

Reputation: 887285

You need pass the element as a parameter:

$(".button").on("click", function(event){
    removeButton(this);
});

function removeButton(elem) {
    $(elem).removeClass("specifiedClass");
}

Upvotes: 5

Related Questions