Kivylius
Kivylius

Reputation: 6557

Trigger a click event with parameters

I have an click function that I want to trigger outside of the function with parameters.

<div id="menubar">
    <a id="menu_file_open">File Open</a>
    <a id="menu_file_save">Save File</a>
</div>


$("#menubar a").click(function(event){

    var menu_item = $(this).attr('id');
    var $context = $(this);

    switch(menu_item){

        case 'menu_file_open':
             //Do menu file open dialog
        break;

        case 'menu_file_save': break;

    }

});

$('#menubar a').trigger('click'); //not working (ID,context not defined);

How would I pass in the ID and the context of the div as it was actually clicked.

Upvotes: 7

Views: 6838

Answers (2)

user278064
user278064

Reputation: 10170

It works for me:

<div id="menubar">
    <a id="click_me" href="#">Click me</a>
    <a id="dont_click" href="#">Don't click</a>
</div>

$("#menubar a").click(function(event){
    var menu_item = $(this).attr('id');
    var $context = $(this);

    //....
});

$('#menubar a#click_me').click();​ // or $('#menubar a#dont_click').trigger('click');

Upvotes: 6

FishBasketGordo
FishBasketGordo

Reputation: 23142

You can pass and retrieve arbitrary data to a jQuery event handler, like so:

$(selector).click({ dataItem1: 'value1', dataItem2: 'value2' }, function(e) {
    var val1 = e.data.dataItem1,
        val2 = e.data.dataItem2;
});

However, because your code is working here, I suspect that there may be another problem, like the jQuery library isn't loaded or there is an error else where in your scripts.

Upvotes: 4

Related Questions