treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Change background of div according to hash url

  • Hello all,

    I'm a novice when it comes to CSS/jQuery but trying my best to pick it up fast..

    I am using a slider as my main content box. I have 3 sections, each of which is accessible with a hash URL.

    I was then wondering if it's at all possible to change the background of a random div (my logo), according to which hashURL (section) is selected?

    Thank you
  • Anyone?

    Would really appreciate some help on this!

    Thanks
  • Yes, it is possible, but it would make it easier for us to help you if you shared, or better yet provided a demo (using jsFiddle.net) with some example code.
  • Try something like this.
    function cssChangeBasedOnHash() {

    switch ( window.location.hash ) {
    case '#random-hash':
    var backgroundColor = '#333'
    break;

    case '#another-hash':
    var backgroundColor = '#222'
    break;

    case '#chicken':
    var backgroundColor = '#f1f1f1'
    break;

    default: // fallback
    var backgroundColor = '#fff'
    break;
    };

    $('#something').css('backgroundColor', backgroundColor);

    }; // cssChangeBasedOnHash()

    $(document).ready(function() {

    cssChangeBasedOnHash();


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

    cssChangeBasedOnHash();

    }); // window.bind.hashchange

    }); // dom.ready


    The switch/case detects the hash names. Change those to your desired hash names. I've set variables depending on what hash is detected. You can place any javascript in there. Functions, objects, whatever.
  • Thanks guys.

    Jamy, really appreciate your help - however could I have some more information - Where would that code go? Where do I reference the background images?

    Mottie, you're right.

    I've uploaded my progress so far to http://www.carlosrios.co.uk

    Like I said before I'm a novice so apologies for what is probably a mess of a code.

    As I explained before I would basically like to have the yellow circle change colour as the user scrolls through the navigation menu. I figure the best way to do this would probably be to make use of a sprite with 3 different coloured circles.


    Thank you so much!

  • jamy_sa has given you some javascript, so it would [usually] go inside the
    <head>
    tags of your page, inside their own script tags. Like this:


    <script type="text/javascript">
    //... all the javascript, i.e.

    $(document.ready(function() {
    cssChangeBasedOnHash();
    }); // dom.ready

    </script>
  • I get that bit, but I don't understand how I would link all of that code so that the picture I use for my logo changes between 3 different ones?

    thanks!
  • here you are, have a look at this:

    http://jsfiddle.net/jFyZ8/1/

    using a sprite like you mentioned and jquery
  • I updated that slightly to look more like the example I supplied previously:

    http://jsfiddle.net/jFyZ8/3/
  • Thank You so much. You guys are amazing will check out what you guys have posted when I get home. Thank you once again!
  • Sorry to bother you guys discussion. Then, How can I add a class on the menu in according the URL in the browser?
    And again. I think we can just use CSS :target????
  • @Hompimpa why dont you create a separate thread for that and explain a little more with an example.

    as for using :target - It isn't well enough supported to use for something that is 'required' on a web page. Also the javascript works on hash change - so its not necessary to click on an anchor link to change the hash, you can type it in yourself into the url bar, hit enter and it will change correctly. You could link someone with a custom hash and it will load with that hash 'enabled'.
  • Hey guys.

    Massive thanks to you both jamy_za and sheepysheep60, it's worked!


    edit: I think i was a bit premature in my celebrations.

    I've uploaded my progress to http://www.carlosrios.co.uk once again.

    if you type in the address bar, #contact and press enter, you're taken to the contact page, but the logo div doesn't change.

    Can this be fixed?




    One more little thing... (sorry :| )

    I'm using 'transify' to fade in the bottom-borders below my navigation. Could a similar solution be applied to my logo div so it fades as it flicks through the different colours!?!?

    Thanking you muchly!
  • It's working for me... perhaps it's happening in a specific browser? I'm using the latest version of Chrome and it looks like it's working in FF as well.

    BTW - Loved the images you used Jamy :P
  • @jamy_za: Like the menu above. When you are on the forum page, the "forum menu" color will be changed. I think it was done by adding active class for example, on the menu based on the url. I think I've got the answer from Stackoverflow:

    var path = window.location.href; // Just grabbing a handy reference to it
    $('ul a').each(function() {
    if (this.href === path) {
    $(this).addClass('active');
    }
    });
  • I've tried it on chrome, safari and internet explorer.

    If I have the 'contact' item selected in the menu. If I refresh the page, the content displayed will still be the 'contact' page but the logo flicks back to the first image used. I've changed the order of the images on the sprite and it keeps happening. Whatever the first image is, it's what automatically gets selected if the page is refreshed, or a page is accessed through the hash link.

    I understand you guys have already helped me loads, but would really like to get this fixed. Really appreciate your efforts.

    Carlos
  • Hi Carlos56!

    Try this (demo):
    $(document).ready(function() {

    var updateLogo = function(id) {
    var backgroundPosition = '0 0';
    switch (id.substring(1)) {
    case 'about':
    backgroundPosition = '-80px -75px';
    break;
    case 'contact':
    backgroundPosition = '160px -75px';
    break;
    }
    $(".logo").css("backgroundPosition", backgroundPosition);
    };

    $(".menu-item").click(function(e) {
    e.preventDefault(); // prevent default link behaviour
    updateLogo(this.hash);
    });
    // update logo on page load
    updateLogo(window.location.hash);

    });
  • Hi Mottie,

    Thanks for your help.

    That fixes the revert to the first image when refreshing the page. It doesn't however update the logo when an item is accessed via a hash link. Is this not possible?
  • Anyone?

    If it's not possible to update the logo when accessing an item through a hash link, then is it possible to have the change fade in?

  • Hey sorry haven't been on in a while. It sounds like you could really do with watching something like this:
    http://css-tricks.com/video-screencasts/85-best-practices-dynamic-content/

    not being awkward, but I'm not 100% sure either and I'm sure Chris goes through everything you'll need to know, you'll just need to apply what we've spoken about using a method he uses!
  • Hey Sheepysheep60, thanks for your reply!

    I'll give that a go, thanks for sharing.

    In the meantime, anyone with a solution, PLEASE share it! (-:

    Thanks
  • "That fixes the revert to the first image when refreshing the page. It doesn't however update the logo when an item is accessed via a hash link. Is this not possible?"

    I provided that solution earlier.
  • You did?!

    Where!?!?

    I'm pretty sure I have included all the script you guys have suggested in this thread. I don't think any suggestions have updated the logo when accessing items through the hash url.

    Thanks again!
  • Ahh, sorry the problem with my demo is I forgot to remove the " e.preventDefault(); // prevent default link behaviour" line, try this updated demo.
  • jamy_za, I've made your code look like this..




    function cssChangeBasedOnHash() {

    switch ( window.location.hash ) {
    case '#serv':
    var backgroundPosition = '0px -151px'
    break;

    case '#port':
    var backgroundPosition = '0px -302px'
    break;

    case '#contact':
    var backgroundPosition = '0px -453px'
    break;

    default: // fallback
    var backgroundPosition = '0 0'
    break;
    };

    console.log(window.location.hash);

    $('.logo-item').css('backgroundPosition', backgroundPosition);

    }; // cssChangeBasedOnHash()

    $(document).ready(function() {

    cssChangeBasedOnHash();


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

    cssChangeBasedOnHash();

    }); // window.bind.hashchange

    }); // dom.ready


    It's not working though? :(

    Just to clarify the '#serv' is just referring to what goes in ' href="" ' - within the HTML right?? I can see your code works in your demo, but for some reason It's not happening at my end. Must be the code.. or my slider maybe..


    Also Mottie your method does allow me to refresh the page once accessed through a hash link and update the logo, but it doesn't do it automatically.

    Could my slider have something to do with it?!

    I appreciate all the time you guys have given me- thank you.

  • Edit: thought something had solved it but it's not the case. Sorry.
  • Example with backgroundColor changed to backgroundPosition

    I've used Chris' frog sprite as the background image =)
  • it's not showing up :(
  • It's the same link - but I've fixed the href problem.
  • @jamy_za thank you so much for all your help.

    It's finally working - it's quite interesting to see how different methods achieve things in different ways.

    Before, the change of logo would happen almost instantly after the click. It now happens with a delay which kinda coincides with the page load.

    I realise I'm pushing it ever so slightly and should've probably started paying you guys a long time ago, but literally just a quick example of how a fade transition could be introduced to work with @jamy-za 's solution, would be extremely appreciated!

    Thank you once again all.

    Carlos