I have an element with an onclick method.
I would like to activate that method (or: fake a click on this element) within another function.
I
If you're using JQuery you can do:
$('#elementid').click();
I haven't used jQuery, but IIRC, the first method mentioned doesn't trigger the onclick
handler.
I'd call the associated onclick
method directly, if you're not using the event details.
var clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var element = document.getElementById('element-id');
var cancelled = !element.dispatchEvent(clickEvent);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
element.dispatchEvent is supported in all major browsers. The example above is based on an sample simulateClick() function on MDN.
For IE there is fireEvent() method. Don't know if that works for other browsers.
Once you have selected an element you can call click()
document.getElementById('link').click();
see: https://developer.mozilla.org/En/DOM/Element.click
I don't remember if this works on IE, but it should. I don't have a windows machine nearby.