Mustapha Aoussar
Mustapha Aoussar

Reputation: 5923

How to create a function for click event?

I have a click event, and within the event handler there's a function that I want execute after the click to change Class of the clicked button from A (by setting timeout) to B.

I tried with this, but this didn't work (see jsFiddle):

Button.click(function(){
    function myFunction(x,y){
        $(this).addClass(x);
        alert(x);

        $(this).addClass(y);
        alert(y);
    }
});


setTimeout(function(){
    myFunction("aaa","bbb");
}, 100);
myFunction("ccc","ddd");

How can I get the function work after the click event?
Any help is appreciated. Thank you very much.

Upvotes: 1

Views: 126

Answers (3)

chris.ribal
chris.ribal

Reputation: 457

Your myfunction() is defined only, if the button was clicked. Try sourcing it out:

var Button = $("#button");

function myFunction(x,y){
    Button.addClass(x);
    alert(x);

    Button.addClass(y);
    alert(y);
}

Button.click(function() {
    myFunction('aaa','bbb');
});

setTimeout(function(){
    myFunction("aaa","bbb");
}, 100);

myFunction("aaa","bbb");

Upvotes: 4

Blake Simpson
Blake Simpson

Reputation: 1088

I think this is what you're looking for. It's similar to the other answers but only calls the function when the button is clicked.

var button = $('button#test');

function myFunction(x,y){
    button.addClass(x);
    alert(x);

    button.addClass(y);
    alert(y);
}

button.click(function(){
    myFunction("aaa", "bbb");
});

I've updated the fiddle here: http://jsfiddle.net/mFd5K/3/

Upvotes: 1

Minko Gechev
Minko Gechev

Reputation: 25682

The function myFunction is defined in different lexical scope.

Use this instead:

//You don't want to define the function each time the button is clicked
function myFunction(x,y){
    $(this).addClass(x);
    alert(x);

    $(this).addClass(y);
    alert(y);
}

Button.click(function(){
    var self = this;
    setTimeout(function(){
        myFunction.call(butto, "aaa","bbb");
    }, 100);
});

Upvotes: 0

Related Questions