How can I synthesize a browser click event on a div element?

Using the buttons, I can call the click() method on them to create a click. However, DIVs do not have this method in all browsers. However, I can connect event listeners to them (either set .onclick="..." or add an event listener).

Is there a way for me to “synthesize” clicking on such an element programmatically, but without using jQuery ? Ideally, this does not depend on the particular method of registering listeners (so just calling eval(div.onclick) will not work for me) and works in all modern browsers.

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

+4
source share
2 answers

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

This is a fully cross browser and fires the specified event on elements returned by the selector engine. I am sure you can extract the code you need from it.

If not, here is what you need. Replace the element, well, the element. And enter 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); } } 
+5
source

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

See dom w3c spec for more details.

+3
source

Source: https://habr.com/ru/post/1341875/


All Articles