0

I'm trying to understand how location.hash works in jQuery, for that, I'm trying to begin from the most basic form, and then once I get that right I'd go deeper, but sadly I'm already stuck at what I think should be a simple thing.

Here's my code I created modifying someone else's code I found in a post here:

$(document).ready(function(){

$("body").css("background-color", "#FF0");

$(window).bind( 'hashchange', function( event ) {

    if (window.location.hash == "red"){
        $("body").addClass("red");
    } else if (window.location.hash == "green") {
        $("body").addClass("green");
    }

    event.preventDefault();

});

$(window).trigger("hashchange");

});

And here's the page http://dlacrem.16mb.com/dlatest/hash.html

Now, as I said, I'm trying to learn so there are probably 80 mistakes in 10 lines :D but, shouldn't it be adding the red class to the body when I go to hash.html#red?

I'm using the BBQ plugin by Ben Alman

Regards, and thanks for any help that comes my way!

Dlacrem
  • 71
  • 3
  • 10

1 Answers1

2

window.location.hash includes the hash symbol.

if (window.location.hash == "#red"){
    $("body").addClass("red");
} else if (window.location.hash == "#green") {
    $("body").addClass("green");
}

Additionally, your inline-style that you set to make the body yellow will override anything you do with a class (unless you use !important, but don't do that!), so you'll want to make it yellow in the stylesheet rather than inline.

http://jsfiddle.net/4SwnQ/

You'll note however that once you make it red, then green, it stays green. This is because you never actually remove the classes, so it takes on the one that has the highest specificity (green in this case since it is last in the stylesheet.) To remedy this, you'll want to also remove the other class.

http://jsfiddle.net/4SwnQ/1/

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • ...unless you use `!important`, which you really shouldn't. – Blazemonger Mar 24 '14 at 14:53
  • Not *anything*, just most things ;) – CodingIntrigue Mar 24 '14 at 14:53
  • 1
    eh, true. Bad idea to use `!important`, i didn't consider it an option! – Kevin B Mar 24 '14 at 14:53
  • wow, I think it works, so it was that simple huh? :D I'll mark it as correct once I'm allowed to. Thank you so much – Dlacrem Mar 24 '14 at 14:57
  • Oh, the yellow thing was just to test if jQuery was working, because I couldn't understand why it wasn't adding the class, don't pay attention to it :P thanks guys – Dlacrem Mar 24 '14 at 15:04
  • The first thing you should have tested in this case was console.log(window.location.hash) before the if statement to see what was being compared in the conditional. That should have immediately pointed out this issue. – Kevin B Mar 24 '14 at 15:05