Javascript click function

I have code that works fine in IE, but unfortunately not in Google Chrome / Firefox.

It relies on calling the click () event on a button from javascript. Reading around it seems like it is an extension of IE (doh). Is there a way to do something like this in chrome + firefox? To clarify, it executes a click event on a specific button, rather than processing what happens when the user clicks a button.

thank

Code for those who requested it:

function getLinkButton(actionsDiv)
{
    var hrefs = actionsDiv.getElementsByTagName("a");
    for (var i=0; i<hrefs.length; i++)
    {
        var id = hrefs[i].id;
        if (id !=null && id.endsWith("ShowSimilarLinkButton"))
        {
            return hrefs[i];
        }
    }
    return null;
}

function doStuff()
{
  //find the specific actions div... not important code...
  var actionsDiv = getActionsDiv(); 
  var linkButton = getLinkButton(actionsDiv);

  if (linkButton != null)
  {
    if (linkButton.click)
    {
        linkButton.click();
    }
    else
    {
        alert("Cannot click");
    }
  }
}

I really don't want to use jQuery unless absolutely necessary

+3
source share
4 answers

I think you are looking for element.dispatchEvent:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

" onclick ", , , " onclick ". , , .

, x- :

if (linkButton != null) 
{ 
  if (linkButton.fireEvent) 
    linkButton.fireEvent("onclick"); 
  else 
  { 
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
                               0, 0, 0, 0, 0, false, false, false, false, 0, null);
    linkButton.dispatchEvent(evt);
  } 
} 
+2

onclick crossbrowser:

<input type="button" onclick="something()" value="" />

, , , : setAttribute, onClick -

+1

OnClick = "methodcall();" ...

0

you can use the onClick attribute or if you need more features look at jQuery and the events it offers: http://api.jquery.com/category/events/

0
source

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


All Articles