March 9, 2013

jQuery simulate click

Question by Bwyss

I want to trigger a function when the page is loaded, I can see here: jQuery call function after load that there are many ways to do this.
However when I add $('#button').click in front of my function then the ‘getType function’ is not recognized. For example:

$('#button').click(function getType(id) {
    //...some code
});

error: getType is not defined

What am I doing wrong?

Answer by Starx

The .click() method requires a callback function. So you can do something like this instead:

//Define your function somewhere else
function getType(id) {
    //...some code
}

$('#button').click(function() {
    getType($(this).attr('id')); //Execute it when its clicked.
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!