levik
levik

Reputation: 117529

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.)

Upvotes: 4

Views: 2715

Answers (2)

Olical
Olical

Reputation: 41362

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);
    }
}

Upvotes: 5

vbence
vbence

Reputation: 20333

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

For more see the dom w3c spec.

Upvotes: 3

Related Questions