Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Last active May 1, 2018 01:07
Show Gist options
  • Select an option

  • Save allenhwkim/c14a35b84e2966aa04d1769e42f48eb1 to your computer and use it in GitHub Desktop.

Select an option

Save allenhwkim/c14a35b84e2966aa04d1769e42f48eb1 to your computer and use it in GitHub Desktop.
function fireEvent(el, type, options) {
var event;
if (type === 'click' || type.match(/^mouse/)) {
event = new MouseEvent(type, options);
} else if (type.match(/^key/)) {
event = new KeyboardEvent(type, options);
} else if (type.match(/^touch/)) {
event = new TouchEvent(type, options);
}
el.dispatchEvent(event);
}
<html>
<body>
<div id="test-div" style="border: 1px solid #ccc"
onclick="myEvent(event)"
onmousedown="myEvent(event)"
onmouseup="myEvent(event)"
onkeydown="myEvent(event)"
onkeyup="myEvent(event)"
onkeypress="myEvent(event)"
ontouchstart="myEvent(event)"
ontouchmove="myEvent(event)"
ontouchend="myEvent(event)"
>
<br/>
Target:
<br/>
#test-div(Event will be fire on this element)
<br/>
<br/>
</div>
Fire the following event programmtically on the target.
<div>
<button onclick="fireEvent(target, 'click')">click</button>
<button onclick="fireEvent(target, 'mousedown')">mousedown</button>
<button onclick="fireEvent(target, 'mouseup')">mouseup</button>
<br/>
<button onclick="fireEvent(target, 'keydown', {key: 'Enter'})">keydown</button>
<button onclick="fireEvent(target, 'keyup', {key: 'Enter'})">keyup</button>
<button onclick="fireEvent(target, 'keypress', {key: 'Enter'})">keypress</button>
<br/>
<button onclick="fireEvent(target, 'touchstart')">touchstart</button>
<button onclick="fireEvent(target, 'touchmove')">touchmove</button>
<button onclick="fireEvent(target, 'touchend')">touchend</button>
</div>
Log:
<div id="log"></div>
<script>
var target = document.getElementById('test-div');
function fireEvent(el, type, options) {
var event;
if (type === 'click' || type.match(/^mouse/)) {
event = new MouseEvent(type, options);
} else if (type.match(/^key/)) {
event = new KeyboardEvent(type, options);
} else if (type.match(/^touch/)) {
event = new TouchEvent(type, options);
}
el.dispatchEvent(event);
}
function myEvent(event) {
console.log('event fired', event);
document.getElementById("log").innerHTML = event.type + " event is fired on #" + event.target.id;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment