Thanks to a question asked earlier, I've noticed that the jQuery .trigger()
(and obviously its shorthand .click()
) don't fully work on hyperlinks. The event gets triggered perfectly fine, it's just as if it adds preventDefault()
to it?
I was wondering why this is happening? Not looking for a solution because I know it would be easy to just grab the href attribute value and use JS to navigate towards the url instead.
Proof of concept:
$(document).ready(function(){
// Method 1
var btn1 = document.getElementById('btn1');
var link1 = document.getElementById('link1');
btn1.addEventListener('click', function (e) {
fireEvent(document.getElementById('link1'), 'click');
});
link1.addEventListener('click', function (e) {
console.log('Click on link1 triggered.');
});
function fireEvent(node, eventName) {
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
var eventClass = "";
switch (eventName) {
case "click":
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true);
event.synthetic = true;
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
var event = doc.createEventObject();
event.synthetic = true;
node.fireEvent("on" + eventName, event);
}
}
// Method 2
$(document).on('click', '#btn2', function(e){
$('#link2').trigger('click');
});
$(document).on('click', '#link2', function(e){
console.log('Click on link2 triggered.');
});
// Method 3
$('#btn3').click(function(e){
$('#link3').click();
});
$('#link3').click(function(e){
console.log('Click on link3 triggered.');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>jQuery click / trigger events not following hyperlinks</h4><br/>
Method 1: Using pure JS<br/>
<button id="btn1">Button 1</button>
<a id="link1" href="https://google.com">Google</a><br/><br/>
Method 2: Using jQuery .on and .trigger methods<br/>
<button id="btn2">Button 2</button>
<a id="link2" href="https://google.com">Google</a><br/><br/>
Method 3: Using jQuery .click method<br/>
<button id="btn3">Button 3</button>
<a id="link3" href="https://google.com">Google</a>
A jsFiddle in case you want to play around with it yourself: https://jsfiddle.net/ap8whL9u/