I know I can use event.preventDefault()
to stop a link from being followed. But I only want to prevent the default action on a plain left-click or touch-tap. shift-left-click, ctrl-left-click, right click, and middle click should all perform the default action.
How can I detect a plain left-click or touch tap?
You can check MouseEvent properties like button , altKey , shiftKey & ctrlKey to do this
document.getElementById('test').addEventListener('click', function(event) { snippet.log('button: ' + event.button); snippet.log('ctrlKey: ' + event.ctrlKey); snippet.log('shiftKey : ' + event.shiftKey); snippet.log('altKey : ' + event.altKey); if (event.button == 0 && !event.ctrlKey && !event.shiftKey && !event.altKey) { event.preventDefault(); } })
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> <a id="test" href="http://stackoverflow.com/">test</a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.