1

I'm trying to change my body's background color to a random color every time a nav-bar link is clicked.

I got it so that a random color gets changed the first time a link is clicked - but when a different link is clicked, nothing changes.

Any tips?

HTML:

    <div class="nav">
      <ul id="show">
        <li id="link1"><a href="#portfolio">Portfolio</li></a>
        <li id="link2"><a href="#about">About</li></a>
        <li id="link3"><a href="#email">Contact</li></a>
        <hr/>
      </ul>
    </div>

JS:

$(function() {

     var colors = ['red', 'blue', 'green', 'grey'];

     var randColor = colors[Math.floor(Math.random()*colors.length)];

     $('.nav a').click(function() {
         $('body').css('background-color', randColor);
     });
});
2
  • 2
    Your HTML structure is invalid. It’s supposed to be <li><a>…</a></li> and not <li><a>…</li></a>. And remove the <hr/> inside the <ul>. <ul>s and <ol>s can only have <li>s as child elements. Commented Sep 30, 2015 at 1:00
  • Based on your function I made this codepen.io/eirenaios/pen/EmYBBP Commented Apr 12, 2017 at 7:43

2 Answers 2

3

Because you only generate one random number and keep using it, move it inside of the click method.

Sign up to request clarification or add additional context in comments.

Comments

1

In each click you need to find a new random color, in your case the randColor variable is updated only once on the dom ready, in the click handle the same value is used all the time.

$(function() {

  var colors = ['red', 'blue', 'green', 'grey'],
    color;

  $('.nav a').click(function() {
    var randColor;
    do {
      randColor = colors[Math.floor(Math.random() * colors.length)];
    } while (color == randColor);
    $('body').css('background-color', randColor);
    color = randColor;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="nav">
  <ul id="show">
    <li id="link1"><a href="#portfolio">Portfolio</a></li>
    <li id="link2"><a href="#about">About</a></li>
    <li id="link3"><a href="#email">Contact</a></li>
  </ul>
  <hr/>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.