WebMasterCampus
WEB DEVELOPER Resources

Javascript Trigger or Create an Onclick Event Manually

Learn Trigger or Create an Onclick event manually using JavaScript


Javascript Trigger or Create an Onclick Event Manually

Creating or triggering an Onclick event manually is easy using Javascript & jQuery. We will guide how to use latest Event method wchich is supported in all latest browsers. Also, the createEvent that is old-fashioned way to implement custom events.

Creating custom Onclick events

 <a id="run" href="#"  onclick="return a_click()">Run</a>
 <button onclick="b_click()">Click me to to execute a_click()</button>

<script>

function a_click(){
    console.log("A tag click event fired.")
}

function b_click(){
    //Supported by Modern browser
    var event = new Event('click');
    document.getElementById("run").dispatchEvent(event);
}

</script>

Trigger custom Onclick events with jQuery

Now, suppose we are using jQuery on click to run code if manual click trigger.


<a id="run" href="#">Run</a>
<button onclick="b_click()">Click me to to execute a_click()</button>

<script src="https://code.jquery.com/jquery-git.js"></script> 
<script>
$(document).ready(function(){

    $('#run').on('click', function(){
        console.log('a tag click event just triggered.')
    })

    $('#button1').on('click', function(){

        $('#run').trigger('click');

    })

});
</script>

Creating custom Onclick events using createEvent

createEvent is The old-fashioned way to create and create custom events. The event can be of any legitimate event type, and should be initialized before use.


<a id="run" href="#"  onclick="return a_click()">Run</a>
<button onclick="b_click()">Click me to to execute a_click()</button>

<script>

function a_click(){
    console.log("A tag click event fired.")
}

function b_click(){
    //Supported by old browsers like IE10
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", false, true);
    document.getElementById("run").dispatchEvent(evt);
}

</script>
Created with love and passion.