Clicking a link does not change the hash location

I am working on a web application that uses the onHashChange event listener in some situations, and manually clicking on the link with href="#hash" works fine. But when I start click on the same link using jQuery $('a[href=#"hash"]').trigger('click') or $('a[href=#"hash"]').click() hash in the address bar does not change.

Is this something I'm doing wrong? or am I using a different 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'); 
+5
source share
3 answers

What you wrote is true (enough to debug jQuery source code): the trigger event does not work at anchor.

To achieve what you are trying, you can get the dom element and then run the click:

 $('a[href="#hash"]').get(0).click() 

This will work.

+1
source

The new guy, we hope, did not offend himself. I just thought maybe something in this code that I use on my site might help you. This is similar to what you are 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; }); }); }); 
+4
source

The click method (when using jquery ) fires click events that you register using el.click(function.. and el.on('click', function...

You can create a new MouseEvent and send it directly to the corresponding 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 for the element (which will not use the jquery click function, but the browser function click ):

 $('a[href="#hash"]')[0].click() 

Please note that this code may not work in multiple browsers due to security concerns.

+2
source

Source: https://habr.com/ru/post/1262231/


All Articles