0

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?

2 Answers 2

5

You need pass the element as a parameter:

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

function removeButton(elem) {
    $(elem).removeClass("specifiedClass");
}
Sign up to request clarification or add additional context in comments.

2 Comments

oh wow. its working perfectly. awesome! also, is it recommended to put it as removeButton(event)? Or should I put it as some other variable so as to avoid conflict?
You are working with an element .. I would make it elem like in the example.
1

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.