robophil
robophil

Reputation: 13

Change the background image of a div depending on which link is selected in the navigation

i'd like to change the background image of a div depending on wich link is selected in my navigation!

exemple : let's say I have a menu item called :

#nav li.menu-item-59

when the link is selected it changes to

#nav li.menu-item-59.selected a

I'd like that whenever one of the menu item is selected the background image of the div footer change to a different file...

I've read some articles about sibling operators but can't seem to make it work and I'm not sure it is the best way to go .. can anyone help? thanks ! :D

Upvotes: 1

Views: 108

Answers (2)

Lost Left Stack
Lost Left Stack

Reputation: 1952

It looks like you're using JS to add the class of selected to the menu. At the same time you're adding that, also add the the menu item name to the footer. something like:

var menuName = $(this).attr('id');
$('.footer').addClass(menuName);

Then in your css for the footer, add the class to the end of the element:

.footer.menu-item-59 {
  // background goes here
}

based on your fiddle below, try:

$(window).scroll(function(){   
  for(var i = 0; i < sections.length; i++)
    if($(window).scrollTop() +5 >= sections[i].top &&
    $(window).scrollTop() <= sections[i].bottom){
      sections[i].link.addClass('selected')
      .siblings().removeClass('selected');
      var selection = 'selected' + i; // new stuff starts here
      $('footer #flag').removeAttr('class');
      $('footer #flag').addClass(selection);
    }
});

Upvotes: 1

user2375017
user2375017

Reputation:

I don't know about sibling operators but this might work...

save all the images in one place. give all links the same class. for this example ive used 'yourmenuclass'. then query the document and listen for which one has been clicked. then in the switch statement to assign a different image, depending on which one has been clicked.

    function init() {
    [].forEach.call(document.querySelectorAll('.yourmenuclass'), function (el) {
        el.addEventListener('click', change);
    });

    function change() {

        if (this.id == 'firstlink') {
            var back = document.getElementById("footername");
            back.style.backgroundImage =" url('http://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Ferns02.jpg/220px-Ferns02.jpg')";
        }
        if (this.id == 'secondlink') {
            var back = document.getElementById("footername");
            back.style.backgroundImage ="url('http://www.dailyshame.co.uk/wp-content/uploads/2012/09/badger.jpg')";
        }

    }
}


onload = init;

if you are using simple anchors then this may not work, but should be fine for buttons or image inputs.

js fiddle

Upvotes: 0

Related Questions