Pages

Showing posts with label Cross Browser. Show all posts
Showing posts with label Cross Browser. Show all posts

Invoking mouse events through JavaScript

Handling Mouse Events through Java script

In some scenarios, we may need to invoke a button click through script. We can write element.click(), but that will not work in all the browsers. We may need to do this in another way, please check the below code snippet.


function invokeSaveClick(saveElementId) {
    var e = document.createEvent('MouseEvents');
    e.initEvent('click', true, true);
    document.getElementById(saveElementId).dispatchEvent(e);
}

Dynamically assign a function to event in javascript

In javascript, using code we can assign function to the events of the elements.

In general, we can assign the function name to the event name directly, Please see the below example.

var element = document.getElementById("testElement");
element.onclick = DynamicFunction;

function DynamicFunction()
{
 alert("sample function");
}


Consider a scenario where you have to assign a function with parameters. we cannot do in the below mentioned way. this will throw a script error.

var element = document.getElementById("testElement");
element.onclick = DynamicFunctionWithParameters(x,y);

function DynamicFunctionWithParameters(param1, param2)
{
 alert("sample function");
}


we have to go with a round about way to achieve the same, see the below example.

var element = document.getElementById("testElement");
element.onclick = function(x,y){DynamicFunctionWithParameters(x,y);};

function DynamicFunctionWithParameters(param1, param2)
{
 alert("sample function");
}


I think you know, we can even directly write the function instead writing it separately and assigning it to the event later. the below example explains this. while mentioning this way we cannot have the function name, and also the same function cannot not be reused.

var element = document.getElementById("testElement");
element.onclick = function(param1, param2)
{
 alert("sample function");
};