6

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');
Farid Rn
  • 3,167
  • 5
  • 39
  • 66
  • Can you demonstrate this using a fiddle? – Anubhav Jan 03 '17 at 15:58
  • Do you `preventDefault()` in your click handler? – AndFisher Jan 03 '17 at 16:00
  • 1
    Silly Question. Why trigger a click on the link? Why not just handle it all programatically? – allnodcoms Jan 03 '17 at 16:09
  • @allnodcoms 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! – Farid Rn Jan 03 '17 at 16:18
  • @FaridRn - I have used this method before, but rather than going through the link, just set 'window.location'... Lot simpler. – allnodcoms Jan 03 '17 at 16:24
  • @gaetanoM I really liked gaetanoM answer. getting first item from jquery selector object works! – Farid Rn Jan 03 '17 at 16:29

3 Answers3

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;
    });
  });
   });
  • 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! – Farid Rn Jan 03 '17 at 16:09
  • I didn't know about anchor.hash +1 – Musa Jan 03 '17 at 16:17
  • 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 [codepen](http://codepen.io/awaybackhome/full/WomzKM/) – awaybackhome Jan 03 '17 at 16:19
  • @awaybackhome Your answer might not help me, but believe me, it might help another developer. +1 for motivating a new user. :) – Farid Rn Jan 03 '17 at 16:24
3

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.

gaetanoM
  • 41,594
  • 6
  • 42
  • 61
2

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.

Dekel
  • 60,707
  • 10
  • 101
  • 129
  • Isn't jQuery's own trigger click doing this? – Farid Rn Jan 03 '17 at 16:07
  • 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! – Farid Rn Jan 03 '17 at 16:16
  • 1
    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. – Dekel Jan 03 '17 at 16:18
  • It seems that I was wrong. trigger doesn't work on anchor tags as @gaetanoM pointed. – Farid Rn Jan 03 '17 at 16:27
  • 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). – Farid Rn Jan 03 '17 at 16:39
  • 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. – Dekel Jan 03 '17 at 16:41