Skip to content

Edit HTML style after a Javascript redirect

I have 2 HTML pages, 1 CSS file, and 1 javascript file. On each HTML page, I have 2 buttons for the switch by the pages. When I press button 1 I go to page 1, when I press button 2 I go to page 2. I’m trying to change the button color when I switch from the page. Example:

I am the page 1 and I have button 1 with red color and button 2 with white color. When I press button 2 I want:

Url change to HTML page 2 (I know how to do it) Button 1 change to white color (I don’t know how to do it) Button 2 changed to red color (I don’t know how to do it)

this is the code:

script.JS

function clickedbutton2(){
  window.location.href = "page2.html";
  document.getElementById("button1").style.color = 'white';
  document.getElementById("button2").style.color = 'red';
}

function clickedbutton2(){
      window.location.href = "page1.html";
      document.getElementById("button1").style.color = 'red';
      document.getElementById("button2").style.color = 'white';
}

page1.html and page2.html (are equals):

<a href = "javascript: clickedbutton1()" class = "button1">button1</a>
<a href = "javascript: clickedbutton2()" class = "button2">button2</a>

style.css:

.button1 {
color: "red";
}

.button2 {
color: "white;
}

When I click the button, the URL and page change but the colors no.

Answer

You can change the button color based on what page you are on, one way to do it is to add a class (in this case page1 & page2) to the body and use those classes when styling the buttons in the CSS like so:

notice the html stays the same apart from a different class on the body, and the buttons have a different color.

.page1 .button1,
.page2 .button2{
color: red;
}

.page1 .button2,
.page2 .button1{
color: white;
}
<html>
<body class="page1">
<a href="#" class="button1">button1</a>
<a href="#" class="button2">button2</a>
</body>
</html>

.page1 .button1,
.page2 .button2{
color: red;
}

.page1 .button2,
.page2 .button1{
color: white;
}
<html>
<body class="page2">
<a href="#" class="button1">button1</a>
<a href="#" class="button2">button2</a>
</body>
</html>