Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 503
Kivylius Avatar asked Jun 12 '12 18:06

Kivylius


Video Answer


2 Answers

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');
like image 92
user278064 Avatar answered Sep 27 '22 17:09

user278064


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.

like image 34
FishBasketGordo Avatar answered Sep 27 '22 18:09

FishBasketGordo