If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
If you want to run an automated click event more than once, you can write the for loop and call target. click() inside the for loop. It automatically invokes the click of the button until the counter reaches its maximum value and outputs the Triggered event 5 times.
The HTMLElement. 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.
You should use addEventListener() instead."
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.
If you're using JQuery you can do:
$('#elementid').click();
I could be misinterpreting your question, but, yes, this is possible. The way that I would go about doing it is this:
var oElement = document.getElementById('elementId'); // get a reference to your element
oElement.onclick = clickHandler; // assign its click function a function reference
function clickHandler() {
// this function will be called whenever the element is clicked
// and can also be called from the context of other functions
}
Now, whenever this element is clicked, the code in clickHandler
will execute. Similarly, you can execute the same code by calling the function from within the context of other functions (or even assign clickHandler
to handle events triggered by other elements)>
If you're using jQuery, you need to use the .trigger
function, so it would be something like:
element.trigger('click');
http://api.jquery.com/trigger/
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.
Using javascript
you can trigger click()
and focus()
like below example
document.addEventListener("click", function(e) {
console.log("Clicked On : ",e.toElement);
},true);
document.addEventListener('focus',function(e){
console.log("Focused On : ",e.srcElement);
},true);
document.querySelector("#button_1").click();
document.querySelector("#input_1").focus();
<input type="button" value="test-button" id="button_1">
<input type="text" value="value 1" id="input_1">
<input type="text" value="value 2" id="input_2">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With