Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.click() method, browser support

I'd like to use the js method .click() as follows:

document.getElementById(id).click();

But since it is essential that it works, I was wondering of what browsers support the .click() method has.

like image 877
don Avatar asked Oct 30 '12 14:10

don


People also ask

What is Click () method?

click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

Which method is used to set a click event on a button?

jQuery click() Method The click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.

How do you click on javascript?

Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.

What is difference between click and Onclick in jQuery?

So, using a string that is tied to a function, onclick produces an attribute within the binded HTML tag. . click, on the other hand, attaches the function to the property element.


1 Answers

The only browser I have encountered that does not support .click() is Safari. Safari supports .click() on buttons (e.g. <input type="button" />) but not on other elements such as anchor elements (e.g. <a href="#">Click Me</a>).

For Safari, you have to use a workaround:

function click_by_id(your_id)
{
    var element = document.getElementById(your_id);
    if(element.click)
        element.click();
    else if(document.createEvent)
    {
        var eventObj = document.createEvent('MouseEvents');
        eventObj.initEvent('click',true,true);
        element.dispatchEvent(eventObj);
    }
}

Using the above function, you can support 90%+ of browsers.

Tested in IE7-10, Firefox, Chrome, Safari.

like image 169
Alex W Avatar answered Sep 19 '22 05:09

Alex W