0

I would appreciate any help, I think I'm going about writing this code completely wrong. I'd like to change my header colour on the click of the button so it goes BLUE >click> RED >click > GREEN. So far I've only been able to achieve BLUE >click> GREEN. It never goes through three colours. Is there a different way to write the if statements? or a different method I do not know about that would allow me to have somewhat conditional css style changes?

var mySwitch = document.getElementById('header').style.background;


if (mySwitch == "darkblue") {

    document.getElementById("myBtn").addEventListener("click", function(){
        document.getElementById("header").style.background = "red";

    });


}
else if (mySwitch == "red") {

    document.getElementById("myBtn").addEventListener("click", function(){
        document.getElementById("header").style.background = "green";

    });

}

else {
    document.getElementById("myBtn").addEventListener("click", function(){
        document.getElementById("header").style.background = "darkblue";

    });

} 
* {
    margin: 0;
    padding: 0;
list-style: none;
font-family: sans-serif;
}

#header {
    background: darkblue;
    color: white;
    
    display: flex;
    justify-content: space-around;
    height: 12vh;
}
#header h1 {
    text-align: left;
    margin-top: 30px;
}

.main-nav ul {
    padding: 0px;
    font-size: 1.5rem;
    display: flex;
    margin-top: 40px;
}

.main-nav a {
color: white;
padding: 20px;
text-decoration: none;

}
.main-nav a:hover {
color: rgb(255, 148, 148);
}

.hero-section {
background-image: url("https://stackoverflow.blog/wp-content/uploads/2018/01/BrutalLifeCycleJavascript.png");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
height: 80vh;
color: white;
text-align: center;

display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}

button {
    background: black;
    height: 40px;
    width: 80px;
    color: white;
    margin-top: 20px;
    animation: jumpbutton 1s ease-out infinite;
    outline: none;
    border-radius: 15px;
}
<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</head>
<body>

<header id="header">

    <nav class="main-nav">

<ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
</ul>
    </nav>

</header>

<div class="hero-section">

    <h1>JAVASCRIPT</h1>
<p id="paragraph">This is a testing environment</p>
<button type="submit"  id="myBtn"> CLICK ME </button>
</div>


<div class="about-box">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, asperiores!</p>

</div>

<!--  CHANGE HEADER COLOR, BACKGROUND & HERO IMAGE-->
















<!---                 -->
<script src="main.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>



</html>

2
  • first, your script will run only once, second background will return an rgb value, third you cannot read background with style intially Commented Jul 15, 2018 at 21:21
  • just define one single event listener function. Within that, get the current value of the background colour of the element, and use that to determine the next colour Commented Jul 15, 2018 at 21:22

5 Answers 5

2

You don't even need jquery for this. So go with pure javascript. I'd also suggest to use ES6 (const and let over var and much more...).

Instead of adding your if statements around the event handler declaration, put them inside of it (see const color).

Also be aware that the background style has more values than just the color (eg. repeat). You could go for just setting and checking backgroundColor or you can split the background value by space and take the first entry (which is the actual color set).

const header = document.getElementById('header')

document.getElementById("myBtn").addEventListener("click", () => {
  const headerBg = header.style.background.split(" ")[0]
  const color = headerBg == "red" ? "green" : headerBg == "darkblue" ? "red" : "darkblue"
  changeBg(header, color)
})

const changeBg = (n, color) => {
  n.style.background = color
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>

<body>
  <header id="header">

    <nav class="main-nav">

      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
    </nav>

  </header>

  <div class="hero-section">

    <h1>JAVASCRIPT</h1>
    <p id="paragraph">This is a testing environment</p>
    <button type="submit" id="myBtn"> CLICK ME </button>
  </div>


  <div class="about-box">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, asperiores!</p>

  </div>
</body>

</html>

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

1 Comment

Appreciate the explanation.
2

This is the correct Javascript:

When we are listening to the myBtn being clicked, we only need one instance of that, so I moved all of your instances and moved them into one. I also declared the color within Javascript so that you only need to click the button once to activate the colors.

More advanced answer was given in this post by manniL!

document.getElementById('header').style.background = "darkblue"; // Declare the initial background color here, so that you don't have to press "Click Me" twice to get it to work!

document.getElementById("myBtn").addEventListener("click", function(){

var mySwitch = document.getElementById('header').style.background;
  
if (mySwitch == "darkblue") { 

    document.getElementById("header").style.background = "red";

} else if (mySwitch == "red") {

  document.getElementById("header").style.background = "green";

} else {

  document.getElementById("header").style.background = "darkblue";

} 

});
* {
    margin: 0;
    padding: 0;
list-style: none;
font-family: sans-serif;
}

#header {
    background: darkblue;
    color: white;
    
    display: flex;
    justify-content: space-around;
    height: 12vh;
}
#header h1 {
    text-align: left;
    margin-top: 30px;
}

.main-nav ul {
    padding: 0px;
    font-size: 1.5rem;
    display: flex;
    margin-top: 40px;
}

.main-nav a {
color: white;
padding: 20px;
text-decoration: none;

}
.main-nav a:hover {
color: rgb(255, 148, 148);
}

.hero-section {
background-image: url("https://stackoverflow.blog/wp-content/uploads/2018/01/BrutalLifeCycleJavascript.png");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
height: 80vh;
color: white;
text-align: center;

display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}

button {
    background: black;
    height: 40px;
    width: 80px;
    color: white;
    margin-top: 20px;
    animation: jumpbutton 1s ease-out infinite;
    outline: none;
    border-radius: 15px;
}
<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
</head>
<body>

<header id="header">

    <nav class="main-nav">

<ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
</ul>
    </nav>

</header>

<div class="hero-section">

    <h1>JAVASCRIPT</h1>
<p id="paragraph">This is a testing environment</p>
<button type="submit"  id="myBtn"> CLICK ME </button>
</div>


<div class="about-box">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam, asperiores!</p>

</div>

<!--  CHANGE HEADER COLOR, BACKGROUND & HERO IMAGE-->
















<!---                 -->
<script src="main.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>



</html>

3 Comments

Please provide information and don't just paste the code in :)
Care for an explanation whoever down voted? The OP is a beginner to Javascript and I've corrected the Javascript code as also I am a novice to Javascript too? Edit(1): Thanks manniL, I will comment and add notations from now and on, I thought the code was incorrect, appreciate your comment.
Looks way better now @GrandIQ ! Thanks for presenting your solution here and helping out :)
1

The issue in your code is that you keep adding more and more event handlers to the element, instead of having one event handler that adjusts its behavior.

Since you're already including jquery, I hope you'll accept an answer that uses it. You can replace main.js with this code and it should give you the result you're looking for.

$(document).on('click', '#myBtn', function() {
    let color;
    switch (document.getElementById('header').style.background) {
        case 'darkblue':
            color = 'red';
            break;
        case 'red':
            color = 'green';
            break;
        default:
            color = 'darkblue';
            break;
    }
    $('#header').css('background', color);
});

The jquery document click handler is a pattern I find myself using very often. It binds to the document, so that you don't have to worry about running the code after creating the element. If the element exists, even if it was deleted at some point, the handler will trigger when you click on it.

You'll notice that document.getElementById('header').style.background is still regular javascript - that is because using $('#header').css('background') will give you a calculated RGB value that does not match a color name string.

Comments

1

how about something like this just have an array of your colors then on a click increment the index, and use the mod operator to get the correct index.

  $(document).ready(function() {
  let i = 0;
  let colors = ['red', 'green', 'blue','purple', 'orange', 'pink'];
  $('button').click(function() {
    $('.header').css("background-color", colors[i++ % colors.length]);
  })
});

https://jsfiddle.net/s0L4mgea/

Comments

0

I had the same issue, after much searching, i have this solution, try it...

// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('#target {color: darkseagreen}');

// Apply the stylesheet to a document:
document.adoptedStyleSheets = [sheet];

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.