Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I synthesize a browser click event on a DIV element?

With buttons, I can call the click() method on them to have a click generated. DIVs however don't have this method on all browsers. Yet I can attach click event listeners to them (by either setting .onclick="..." or adding an event listener).

Is there any way for me to "synthesize" a click on such an element programmatically, but without using jQuery? Ideally this will not be dependent on a specific way of the listeners being registered (so simply calling eval(div.onclick) will not work for me), and work in all modern browsers.

(For the curious, I need this for automated testing, not tricking users.)

like image 944
levik Avatar asked Feb 25 '23 22:02

levik


2 Answers

I recently wrote a function to do just this into my library, it can be found in the GitHub repository here.

It is completely cross browser and triggers the specified event on the elements returned by the selector engine. I am sure you will be able to extract the code you need from it.

If not, here is what you need. Replace element with, well, the element. And type with the type of event, in this case, click.

// Check for createEventObject
if(document.createEventObject){
    // Trigger for Internet Explorer
    trigger = document.createEventObject();
    element.fireEvent('on' + type, trigger);
}
else {
    // Trigger for the good browsers
    trigger = document.createEvent('HTMLEvents');
    trigger.initEvent(type, true, true);
    element.dispatchEvent(trigger);
}

Here is an example implementation.

function simulateEvent(element, type) {
    // Check for createEventObject
    if(document.createEventObject){
        // Trigger for Internet Explorer
        trigger = document.createEventObject();
        element.fireEvent('on' + type, trigger);
    }
    else {
        // Trigger for the good browsers
        trigger = document.createEvent('HTMLEvents');
        trigger.initEvent(type, true, true);
        element.dispatchEvent(trigger);
    }
}
like image 145
Olical Avatar answered Mar 08 '23 17:03

Olical


If your browser is DOM compatible you can use the dispatchEvent(evt) method of the DIV element.

For more see the dom w3c spec.

like image 29
vbence Avatar answered Mar 08 '23 17:03

vbence