Question: Triggering click on a link doesn't change location hash


Triggering click on a link doesn't change location hash

Answers 3
Added at 2017-01-03 16:01

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?


<a href="#hash">Do Something</a>


// Not working

// Not working
Answers to

Triggering click on a link doesn&#39;t change location hash

nr: #1 dodano: 2017-01-03 17:01

The click method (when used by jquery) triggers the click events that you register using the 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);

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):


Note that this code might not work in several browsers due to security reasons.

nr: #2 dodano: 2017-01-03 17:01

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.

  $('a[href^="#"]').on('click',function (e) {

    var target = this.hash;
    var $target = $(target);

    $('html, body').stop().animate({
      'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
      window.location.hash = target;
nr: #3 dodano: 2017-01-03 17:01

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:


This only will work.

Source Show
◀ Wstecz