Triggering click on a link doesn't change location hash

6.4k views Asked by At

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');
3

There are 3 answers

0
gaetanoM On BEST ANSWER

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.

6
Dekel On

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.

4
awaybackhome On

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;
    });
  });
   });