7

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.

6
  • 5
    What you have should work.. provided the link has an ID and the context should be link element. Just a tip: You can just do $('#menubar a').click() instead of .trigger Commented Jun 12, 2012 at 18:04
  • 2
    Also, you may want to filter that down to a specific anchor element rather than triggering the click handler on all of them at once, depending on what you are trying to do of course. Commented Jun 12, 2012 at 18:07
  • 1
    It works: jsfiddle.net/fbkxk. Is jQuery loaded properly? Commented Jun 12, 2012 at 18:09
  • I have more then one item so thanks so I just need to say: $('#menubar a#ID_HERE').trigger('click'); and it works. Thanks you Kevin B. Commented Jun 12, 2012 at 18:13
  • check this it works for more than one elements too jsfiddle.net/joycse06/gPvfc/1 . Though I am not sure if you want to trigger click for all of them at once, Commented Jun 12, 2012 at 18:15

2 Answers 2

6

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');
Sign up to request clarification or add additional context in comments.

3 Comments

Calling click() is just a short cut for calling trigger('click')
You're Right! I always used click() :p. I'll update my post according to your hint!
@CezarisLT: Are u still having the context not defined problem? Because this could mean likely that you've problems with the JQuery library.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.