Triggering click on a link doesn't change location hash
Asked Answered
R

3

8

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');
Rayleigh answered 3/1, 2017 at 15:53 Comment(6)
Can you demonstrate this using a fiddle?Shoreless
Do you preventDefault() in your click handler?Latashialatch
Silly Question. Why trigger a click on the link? Why not just handle it all programatically?Rheotropism
@Rheotropism Imagine a page that when loads with a url hash does something based on url's hash. and changing hash does the same thing. I want to create a default hash that if user opened the page without any hash in url, I simulate clicking on a default button. Sorry if my question doesn't describe the situation very well; but beleive me it's not as silly as you might think it is!Rayleigh
@FaridRn - I have used this method before, but rather than going through the link, just set 'window.location'... Lot simpler.Rheotropism
@gaetanoM I really liked gaetanoM answer. getting first item from jquery selector object works!Rayleigh
D
4

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.

Dorweiler answered 3/1, 2017 at 16:17 Comment(0)
W
5

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;
    });
  });
   });
Weidar answered 3/1, 2017 at 16:5 Comment(4)
So you are manually changing the location hash, right? I'm wondering why click trigger method is not doing the same thing? Once you call trigger('click)` on an element, everything is as user clicks on it but url changes on manual click and not with trigger!Rayleigh
I didn't know about anchor.hash +1Croft
Like I said. It just seemed similar to what I read and I hoped something there would trigger a solution! Sorry. Wish I could help more. I don't know what you mean by manually. The JS works simply after just marking the #locations in HTML. It's here on codepenWeidar
@Weidar Your answer might not help me, but believe me, it might help another developer. +1 for motivating a new user. :)Rayleigh
D
4

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.

Dorweiler answered 3/1, 2017 at 16:17 Comment(0)
R
3

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.

Revanchism answered 3/1, 2017 at 16:0 Comment(6)
Isn't jQuery's own trigger click doing this?Rayleigh
Sorry, but I don't understand. If I trigger click on a link with an actual (url) href, locations gets changed to the given href. But it's not working with a hash-only href. why is that? You are suggesting creating new event for click but I want to know why click is not doing the same thing!Rayleigh
Are you sure it works? I just checked it on chrome/firefox/ie - the $('a').click() on regular link doesn't work... it does nothing.Revanchism
It seems that I was wrong. trigger doesn't work on anchor tags as @Dorweiler pointed.Rayleigh
I faced something else which is confusing me! Is there any difference between $('a[href="#hash"]')[0].click(); and ```$('a[href="#hash"]')[0].trigger('click');`? First is working and second not! jQuery docs says click without params is the same as triggre(click).Rayleigh
As for your first comment - it's also in my answer (you should have read the update correctly). As for the second comment - the second line of your use using trigger on the element (and not on the jquery object), and you can't do this. Open the console and check the errors.Revanchism

© 2022 - 2024 — McMap. All rights reserved.