Home > Net >  How can I make this button change the background of my website when pressed?
How can I make this button change the background of my website when pressed?

Time:01-18

So I like my current background color but want to also have a button that can change it to white for others. I am making it for my website. Please help! I checked the other ones like this and none of them have helped!

#check {
  display: none;
}

.myBtn:active {
  background-color: white;
}

.myBtn:visited {
  background-color: whitesmoke;
}
<button >Click here to change the background color</button>

this is what I have but it's not working

CodePudding user response:

JavaScript will be required to achieve what you are asking for. As you currently have it implemented your CSS styling is styling the button and not the background of the page and the visited anchor is not valid on buttons.

var bkgColorChangeBtn = document.getElementById("backgroundColorChangeButton")

bkgColorChangeBtn.addEventListener('click', function(e) {
  document.body.style.backgroundColor = 'red'
})
<body>
 <button id="backgroundColorChangeButton" class ="myBtn">Click here to change the background color</button>
</body>

Above is a working example of what you are trying to do. Note this won't persist when the user refreshes the page. If you want it to persist you will have to save a user setting into a database and recall the information on page render which goes beyond regular HTML/CSS/JS.

  • Related