0

I would like to write a code to trigger an event in pure javascript without clicking the button.

i would like the solution to be more generic so that it can be apllied to any event. Like if i want to trigger either button click or drop down etc without actual mouse or keyboard activity.

we have seething for submit button without clicking on it--document.formid.submit();

user3196985
  • 7
  • 1
  • 3
  • 1
    You can either use the jQuery `trigger` method, or natively https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events – Gavin May 17 '16 at 10:35
  • you just need to create a javascript function and bind it with whaever action you want. – Hemant Metalia May 17 '16 at 10:35
  • Possible duplicate of [How to trigger event in JavaScript?](http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript) – Vladimir Drenovski May 17 '16 at 10:39

1 Answers1

3

jQuery's trigger method can be used to trigger an event:

https://jsfiddle.net/gRoberts/4xah6nph/

$('#test').click(function(e) {
    alert('jQuery: You clicked me!');
});

setTimeout(function() {
    $('#test').trigger('click');
}, 5000);

or alternatively you can use

var elem = document.getElementById('test');
elem.addEventListener('click', function(e) {
    alert('Navtive: You clicked me!');
});
setTimeout(function() {
    elem.dispatchEvent(new Event('click'));
}, 6000);
Gavin
  • 6,284
  • 5
  • 30
  • 38