I want to trigger a function when the page is loaded. 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?
Just to clarify, in this case I cannot use an anonymous function. Also, it does not matter to me whether I use $(document).ready
or $(window).bind("load", function()
, but using these I still get the “getType is not defined” error.
jQuery click() Method The click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.
trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.
click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
You either have to make your function anonymous:
$('#button').click(function() {
//...some code
});
Or pass the function itself:
function getType() {
//...some code
}
$('#button').click(getType);
If you just want to trigger a click, call .click()
:
$('#button').click();
Also, your id
parameter won't be the element's id
. It'll be the click event object. To get the element's id
, you can refer to the clicked element using this
:
$('#button').click(function() {
var id = this.id;
});
I suggest you read a few JavaScript and jQuery tutorials (in that order).
You are using the inline notation so, you should use an anonymous function (no name function)
your code should be:
$('#button').click(function() {
// do your stuff here
}
);
Beside that, as the titles says, you need to simulate a click
event, right ? if so you better use something like:
$('#button').on('click', function() {
alert($(this).text());
});
// somewhere when you want to simulate the click you call the trigger function
$('#button').trigger('click');
see documentation here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With