JSFiddle - React, Tailwind, and code Playground
by Jim_Toth
HTML
<h1>Simulating clicks with Javascript</h1>
<div>
<button id="testTarget">Click will be simulated here</button>
</div>
<div>
<button id="testTrigger">Trigger a simulated click</button>
<h2>Modifier Keys</h2>
<label for="modifier_control">Control</label><input type="checkbox" id="modifier_control"/>
<label for="modifier_shift">Shift</label><input type="checkbox" id="modifier_shift"/>
<label for="modifier_alt">Alt</label><input type="checkbox" id="modifier_alt"/>
<label for="modifier_meta">Meta</label><input type="checkbox" id="modifier_meta"/>
</div>
CSS
div {
margin-bottom: 1em;
padding: 1em;
border-bottom: 1px solid #DDD;
}
JavaScript
//Just to verify the click worked.
document.getElementById('testTarget').addEventListener('click', function(e){
var msg = '#testTarget got clicked: ',
modifiers = [];
if (e.ctrlKey) {modifiers.push('Control key')};
if (e.shiftKey) {modifiers.push('Shift key')};
if (e.altKey) {modifiers.push('Alt key')};
if (e.metaKey) {modifiers.push('Meta key')};
msg += modifiers.join(', ');
alert(msg);
}, false);
//Just to verify the click worked.
document.getElementById('testTrigger').addEventListener('click', function(){
var options = {
ctrlKey: document.getElementById('modifier_control').checked,
altKey: document.getElementById('modifier_alt').checked,
shiftKey: document.getElementById('modifier_shift').checked,
metaKey: document.getElementById('modifier_meta').checked,
}
simulatedClick(document.getElementById('testTarget'), options);
}, false);
function simulatedClick(target, options) {
var event = target.ownerDocument.createEvent('MouseEvents'),
options = options || {},
opts = { // These are the default values, set up for un-modified left clicks
type: 'click',
canBubble: true,
cancelable: true,
view: target.ownerDocument.defaultView,
detail: 1,
screenX: 0, //The coordinates within the entire page
screenY: 0,
clientX: 0, //The coordinates within the viewport
clientY: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
button: 0, //0 = left, 1 = middle, 2 = right
relatedTarget: null,
};
//Merge the options with the defaults
for (var key in options) {
if (options.hasOwnProperty(key)) {
opts[key] = options[key];
}
}
...