Aaron
Aaron

Reputation: 10440

Using url hash to perform click event

So I have a page that has 3 buttons to filter content on the page.

<section class="solution-filter">
    <div class="wrapper">
        <button class="fact-sheet" data-target_category="fact-sheet" disabled="">Fact sheet</button>
        <button class="demo" data-target_category="demo">Demo</button>
        <button class="apps" data-target_category="apps">Apps and connectors</button>
    </div><!-- /.wrapper -->
</section>

I would like to be able to perform a click on a button depending on the url hash.

For example http://example.com/#demo would perform a click on the <button class="demo" data-target_category="demo">Demo</button>

if ( window.location.hash ) {
    $(document).click($('<button>').data('target_category', (window.location.hash));
}

Upvotes: 1

Views: 2542

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337570

You've got the right idea, although the syntax you're using to raise the click event is not quite right. You need to first use the hash value to select the element, then call click() or trigger('click') on it.

if (window.location.hash) {
  $('.' + window.location.hash.substr(1)).click();
}

Note that the substr() call is used to remove the # from the start of the string.

The above code will work for you when the page loads. If you also want to know when the hash changes after page load you can use the hashchange event of the window:

$(window).on('hashchange', function() {
  if (window.location.hash) {
    $('.' + window.location.hash.substr(1)).click();
  }
});

Upvotes: 3

Satpal
Satpal

Reputation: 133403

You need get the button then trigger click(), $('<button>') will create a jQuery object not target the desired element.

if (window.location.hash)
    $('button[data-target_category="'+window.location.hash.substr(1)+'"]').click();

Upvotes: 2

Related Questions