Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering click on a link doesn't change location hash

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');
like image 495
Farid Rn Avatar asked Jan 03 '17 15:01

Farid Rn


3 Answers

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;
    });
  });
   });
like image 116
awaybackhome Avatar answered Nov 18 '22 23:11

awaybackhome


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.

like image 2
gaetanoM Avatar answered Nov 18 '22 22:11

gaetanoM


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.

like image 2
Dekel Avatar answered Nov 18 '22 23:11

Dekel