Paulo Fino
Paulo Fino

Reputation: 43

Change CSS if URL has hash

I'm trying to change an element's CSS when the URL has a hash in it.
The URL looks like

http://foo.com/base/something#item-itemID

The only static part in the URL is the #item- bit. The something and the itemID bits change. So whenever a URL has #item (dash omitted on purpose) in it I'd like to change

<ul class="side">

into

<ul class="side hashed">

After creating a specific class for this case I managed to compile a piece of JS code based on my poor understanding of JS and JQuery to add this class to the element:

$(function() {
  var loc = window.location.hash;
  if(/^#item/.test(loc)) {
    $('ul.side').addClass('hashed');
  }
});

But it doesn't work.

Please help.
Any suggestions in the right direction greatly appreciated.

Upvotes: 4

Views: 5991

Answers (4)

user1255961
user1255961

Reputation: 1

This way uses PHP to check if the url contains a hash and then if this is the case, you can amend your css however you wish.

<?php

     $url = $_SERVER['REQUEST_URI'];
     $hash = '-';   
     $hashurl = strpos($url, $hash);

     if ($hashurl !== false) {

     echo '

         //add jquery to add and/or remove css class to element.        

     ';

     }

?>

Upvotes: 0

Daniel
Daniel

Reputation: 4946

$(function () {
    var loc = (window.location.hash).split("-");

    if (loc[0] == "#item") {
        console.log("item found");
        //  $('ul.side').addClass('hashed');
    }
});

EDIT: change responsive functionality

Thanks for checking it out. I do not have the error you describe in the comments when committing an isolated test. I did see inconsistencies that may be an issue to the responsiveness. Your code snippet does not look for a hash change, so I adapted it to look for a hash upon page load and also trigger when it gets changed dynamically: http://jsfiddle.net/djwave28/hqdvC/

$(function () {
    if (window.location.hash) {
        getHash();
    }
    $(window).on("hashchange", function () {
        getHash();
    });
});

function getHash() {
    var loc = (window.location.hash).split("-");
    if (loc[0] == "#item") {
        console.log("item found");
        //  $('ul.side').addClass('hashed');
    };
}

There is some odd behavior. When you have a hash in the url and highlight the address bar and hit enter, the page does not refresh. I searched for an answer but there is nothing I could find. Baffled by this I started my own question: Page refresh from address bar with #hash

Upvotes: 1

ArleyM
ArleyM

Reputation: 853

A pure CSS solution (demo)

a[href*="#"] {  
  color: purple; /* contains a hash */  
}   

This will even work on IE7 ;)

This is just the selector, the CSS attributes you'd put in there are whatever values .hashed already has.

Upvotes: 2

spirit walker
spirit walker

Reputation: 304

if (window.location.hash.split('-')[0] == '#item') {
    $('ul.side').addClass('hashed');
}

Upvotes: 3

Related Questions