Setting URL hash with click function then using it (JavaScript tips)


One of the things I am excited to do with this new blog, is to add coding and development tips, tricks, and tutorials. JavaScript is one of my favorite coding languages to work with, so what better place to start?

Here’s a random JavaScript tutorial on how to set a URL hash (or parameter) with a simple on click function, and then detect it and utilize it later.

The below is using jQuery to set a click function on the

.boom

HTML element, and then setting a URL hash to

#boom

So, upon firing the click function the website URL would now have that param, ie.

www.yourwebsite.com/#boom

Setting the hash:

$('.boom').click(function(){
    $(this).fadeTo("slow", 0, function(){
        $(this).remove(),
        $('#BoomNotification').fadeIn('1500');
        window.location.hash = 'boom'; // key
    });
});

This is useful, especially for single page applications – because you can do stuff based on that newly created URL param. Great stuff, eh?

Now, easily detect and use that URL hash or param to do stuff based on it.

if(document.URL.indexOf("#boom") >= 0)
{
    $('span.Welcome').fadeIn(); // sample

    // do, do, do

}

Published by

admin

I’m Cameron Cashwell, I’ve been a Web Developer for 6+ years. I’m always on the look out for exciting new projects and ideas. Wanna work together? http://www.cdev.co/#request

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz