Search code examples
javascriptjqueryfragment-identifier

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

Solution

  • 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.