Search code examples
javascriptjqueryjquery-uijquery-eventsjquery-ui-dialog

Trigger a jQuery Event Handler Assigned in a Different Code Block


I have a case where a click handler is defined/assigned in one jQuery code block (file) and I want to trigger it from another click event defined/assigned in a different jQuery code block. How can I accomplish this?

The following code is a greatly simplified version of what I am trying to accomplish. The behavior I want to see is a JavaScript alert "Element One" when I click #Element2.

Example HTML:

<p id="Element1">Element One</p>
<p id="Element2">Element Two</p>

First jQuery code block:

$(document).ready(function() {
    $('#Element1').click(function() {
        alert('Element One');
    });
});

Second jQuery code block:

$(document).ready(function() {
    $('#Element2').click(function() {
        $('#Element1').click();
    });
});

UPDATE: My original example actually works. I was building upon my field hint jQuery UI Dialog solution, and didn't account for about the 'clickoutside' handler that I was using. Adding a check to for the second element in my 'clickoutside' handler allows the dialog to display.


Solution

  • You need to trigger a click when you click on the first element. You can use the trigger method for this.

    function element1Hanlder () {
        alert('Element One');
    }
    
    $(document).ready(function() {
        $('#Element1').click(function() {
            alert('Element One');
        });
    });
    
    $(document).ready(function() {
        $('#Element2').click(function() {
            $('#Element1').trigger('click');
        });
    });