Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change background-color on click using a variable

Scenario

3 Nav items

<a href='#one'></a> <a href='#two'></a> <a href='#three'></a>

3 Sections

<section id='one'></section>
<section id='two'></section>
<section id='three'></section>...

Make navbar item background-color = section background-color

Basic graphic example https://i.sstatic.net/3VTBG.jpg

JSFiddle http://jsfiddle.net/kolorweb/r871bzz3/

I have managed to get the dynamic color change working using a variable that retrieves the section background-color.

But how do I remove this background-color property when another nav item is clicked..

$('nav ul li a').click(function() {
  $('nav ul li a').removeClass('active');
  $(this).addClass('active');

  // gets #''
  var section_id = $(this).attr('href');

  // this is the variable I want to apply to the relevant nav a on click.
  var section_color = $(section_id).css('background-color');

  // applying variable to the nav item that has been clicked  
  $(this).css('background-color', section_color);

  // HOW DO I THEN REMOVE THIS PROPERTY WHEN ANOTHER NAV ITEM IS CLICKED?




});
nav ul li {
  list-style: none;
  display: inline;
}
nav a {
  text-decoration: none;
  padding: 10px 20px;
}
.active {
  background-color: tomato;
}
#one {
  width: 100vw;
  height: 100px;
  background-color: tomato;
}
#two {
  width: 100vw;
  height: 100px;
  background-color: pink;
}
#three {
  width: 100vw;
  height: 100px;
  background-color: steelblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>
  <ul>
    <li><a href="#one">one</a>
    </li>
    <li><a href="#two">two</a>
    </li>
    <li><a href="#three">three</a>
    </li>
  </ul>
</nav>

<section id="one">One</section>
<section id="two">Two</section>
<section id="three">Three</section>
like image 317
Kolorweb Avatar asked Jan 18 '26 22:01

Kolorweb


1 Answers

Do not remove from other after apply to the active one, but remove from all before:

$('nav ul li a').click(function() {
  $('nav ul li a').removeClass('active');
  $(this).addClass('active');

  // gets #''
  var section_id = $(this).attr('href');

  // this is the variable I want to apply to the relevant nav a on click.
  var section_color = $(section_id).css('background-color');

  // remove from all
  $('nav ul li a').css('background-color', '');

  // applying variable to the nav item that has been clicked  
  $(this).css('background-color', section_color);

});

And a short chained version:

$('nav ul li a').click(function() {
  $('nav ul li a').removeClass('active').css('background-color', '');
  $(this).addClass('active').css('background-color', $($(this).attr('href')).css('background-color'));
});
like image 156
KyleK Avatar answered Jan 20 '26 12:01

KyleK