Mirko Brombin Mirko Brombin - 3 months ago 16
Javascript Question

Add class if hash value exists in page URL

I'm trying to add a class to my div if hash value exists in url:

<script type="text/javascript">
if(window.location.hash) {
alert(window.location.hash);
$(".pinIt").addClass("pinned");
$(".hideIt").addClass("hidden");
$(".changeIt").addClass("changed");
} else {
$(".pinIt").removeClass("pinned");
$(".hideIt").removeClass("hidden");
$(".changeIt").removeClass("changed");
}
</script>


HTML:

<header class="changeIt">
</header>


<div class="heading">
<h1 class="hideIt">Test</h1>
<h2 class="pinIt">
</h2>
</div>


My script show the alert but do not add class.
Where is the problem?

Answer

The problem is your code is being run before pinIt etc exist. You need to wrap it:

$(function(){
    if(window.location.hash) {
        alert(window.location.hash);
        $(".pinIt").addClass("pinned");
        $(".hideIt").addClass("hidden");
        $(".changeIt").addClass("changed");
    } else {
        $(".pinIt").removeClass("pinned");
        $(".hideIt").removeClass("hidden");
        $(".changeIt").removeClass("changed");
    }
});

More info from jquery Here