I want to trigger a ommousedown event on a empty td tag using java script but not using jquery. Any suggestions please
Asked
Active
Viewed 2.8k times
16
-
1Have you tried anything yet..? – Nicklas Pouey-Winger Dec 13 '13 at 13:35
-
This question is a generic version of your specific one: http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript – jasonlfunk Dec 13 '13 at 13:36
-
function simulateClick(){ var event = new MouseEvent('onmousedown', { 'view': window, 'bubbles': true, 'cancelable': true }); var cb = document.getElementById('x'); cb.dispatchEvent(event); } This is the code i have tried result is uncaught exception: [Exception... "Cannot convert WrappedNative to function" nsresult: "0x8057000d (NS_ERROR_XPC_CANT_CONVERT_WN_TO_FUN)" – vinod kumar Dec 18 '13 at 06:35
3 Answers
26
I threw together a CodePen demo for you:
http://codepen.io/anon/pen/lrAxp
var element = document.getElementById('testButton');
if(document.createEvent)
{
element.dispatchEvent(new Event('mousedown'));
}
else{
// Internet Explorer (I think)
element.fireEvent("onmousedown", event);
}
You can also check out this SO post for more info: How to trigger event in JavaScript?
-
-
5I had problems with dispatching `new Event("mousedown")`. It wasn't being caught in my event handler. But if I dispatched `new MouseEvent("mousedown")` then it worked. – ccallendar Aug 08 '19 at 16:10
-
mousedown is undefined regardless of whether you use Event or MouseEvent. I don't know if it was simply removed from javascript but it now will break anything you try to use it in e.g. canvasElem.dispatchEvent(new Event('mousedown', {pageX: 264, pageY: 267})) – David Bandel Jan 28 '22 at 18:04
-
It doesn't work for me (Chrome v.106), but the accepted solution from this thread worked: https://stackoverflow.com/questions/24025165/simulating-a-mousedown-click-mouseup-sequence-in-tampermonkey – van_folmert Oct 23 '22 at 12:17
3
This dispatches mousedown event on every empty td cell (on modern browsers):
var emptyTableCells = document.querySelectorAll("td:empty");
var mousedown = new Event('mousedown');
[].forEach.call(emptyTableCells, function(elem) {
elem.dispatchEvent(mousedown);
});

Samuli Hakoniemi
- 18,740
- 1
- 61
- 74
-5
If you just want something simple you can also use the HTMLElement's click function:
var td = document.getElementsByTagName('td')[0];
td.onclick = function(){
alert('!');
}
td.click();
Here's a fiddle that shows it in action: jsFiddle

tylerargo
- 1,000
- 10
- 13