I'm working on a web application that uses onHashChange
event listener in some situations and manually clicking on a link with href="#hash"
works perfectly well.
But when I trigger click on the same link using jQuery's $('a[href=#"hash"]').trigger('click')
or $('a[href=#"hash"]').click()
hash in address bar is not changing.
Is it something that I'm doing wrong? or I shoud use another method for this purpose?
HTML
<a href="#hash">Do Something</a>
JS
// Not working
$('a[href="#hash"]').click();
// Not working
$('a[href="#hash"]').trigger('click');
New guy here hopefully not making an azz of himself. I just thought maybe something in this code I'm using on my site might help you. It kinda seems similar to what you're describing.
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
What you wrote is true (it's enough to debug jQuery source code): the trigger click event doesn't work on an anchor.
In order to achieve what you are trying you can get the dom element and then fire the click:
$('a[href="#hash"]').get(0).click()
This only will work.
The click
method (when used by jquery
) triggers the click
events that you register using the el.click(function..
and el.on('click', function...
You can create a new MouseEvent
and dispatch it directly to the relevant element:
e = document.createEvent('MouseEvents');
e.initEvent("click", true, true);
$('a[href="#hash"]')[0].dispatchEvent(e)
The above code will work in Chrome, Firefox and IE
Or just use the click
event of the element (which will not use jquery's click
function, but the browser's click
function):
$('a[href="#hash"]')[0].click()
Note that this code might not work in several browsers due to security reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With