How do I update the URL on button click?

Biz Cook

Do you have AJAX on a page and want to change the URL accordingly based on the new content? The following code will get rid of the last bit of the slug on your page and replace it with the data-slug attribute of the button or element you clicked.

Make sure to add an element on the page that has a class of ‘tab‘, and a ‘data-slug‘ attribute from which we will pull and update the slug.

Then set up your jquery click event:

$('.tab').on('click', function(){
     //grab the slug from the element you clicked
     var post_slug = $(this).data("slug");
     history.replaceState({}, '', window.location.href.slice(0, -1));
     history.pushState(null, null, post_slug );
});

…And there you have it!

Last updated by on .

What Are Your Thoughts?

Your email address will not be published. Required fields are marked *