Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery simulate click

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.

like image 530
Bwyss Avatar asked Mar 09 '13 21:03

Bwyss


People also ask

How to click an element using jQuery?

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.

What is trigger click in jQuery?

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.

How do you simulate a click on an element?

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.


2 Answers

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).

like image 149
Blender Avatar answered Oct 13 '22 17:10

Blender


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

like image 26
Abu Romaïssae Avatar answered Oct 13 '22 17:10

Abu Romaïssae