i have a bunch of buttons with the id btn1, btn2 , btn3 etc. and i want to change the background when one button is clicked, for example if btn1 is pressed it gets black but when btn2 is pressed that gets black and btn1 goes back to its original state.
body {
background-color: #fff;
font-size: 62.5%;
}
#background-buttons { text-align: right; }
#background-buttons button {
background-color: #222;
font-family: Roboto Condensed;
color: #fff;
padding: 10px;
outline: none;
border: none;
width: 50px;
height: 50px;
border-radius: 50px;
}
#background-buttons #activated { background-color: #000; }
#background-buttons button:hover { background-color: #555; }
#background-buttons button:active { background-color: #333; }
<div id="background-buttons">
<button id="btn1" onclick="change()">1</button>
<button id="btn2" onclick="change()">2</button>
<button id="btn3" onclick="change()">3</button>
<button id="btn4" onclick="change()">4</button>
<button id="btn5" onclick="change()">5</button>
<button id="btn6" onclick="change()">6</button>
<button id="btn7" onclick="change()">7</button>
<button id="btn8" onclick="change()">8</button>
<button id="btn9" onclick="change()">9</button>
<button id="btn10" onclick="change()">10</button>
</div>
This code on JSFiddle
When a button is clicked loop through all buttons, set their backgroundColor to #222 and set the backgroundColor of the one that was clicked to something else.
Also, in the markup when you call the function change(), pass a parameter this,i.e, change(this).
Updated Fiddle
// el is the button that was clicked
function change(el) {
var all = document.getElementsByTagName('button');
// loop through all buttons
for (i = 0; i < all.length; i++) {
// if the current button is the one that was clicked change its color to 'plum', else '#222'
all[i].style.backgroundColor = all[i] == el ? 'plum' : '#222'
}
}
body {
background-color: #fff;
font-size: 62.5%;
}
#background-buttons {
text-align: right;
}
#background-buttons button {
background-color: #222;
font-family: Roboto Condensed;
color: #fff;
padding: 10px;
outline: none;
border: none;
width: 50px;
height: 50px;
border-radius: 50px;
}
#background-buttons button:hover {
background-color: #555 !important;
}
<div id="background-buttons">
<button id="btn1" onclick="change(this)">1</button>
<button id="btn2" onclick="change(this)">2</button>
<button id="btn3" onclick="change(this)">3</button>
<button id="btn4" onclick="change(this)">4</button>
<button id="btn5" onclick="change(this)">5</button>
<button id="btn6" onclick="change(this)">6</button>
<button id="btn7" onclick="change(this)">7</button>
<button id="btn8" onclick="change(this)">8</button>
<button id="btn9" onclick="change(this)">9</button>
<button id="btn10" onclick="change(this)">10</button>
</div>
Create a CSS class to style the selected button appropriately:
.selectedButton {
background-color: black;
}
Create some library functions to add and remove a class:
var util = {dom:{}};
util.dom.hasClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
return el && re.test(el.className);
}
util.dom.addClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (!util.dom.hasClassName(el, cName)) {
el.className = util.trim(el.className + ' ' + cName);
}
}
util.dom.removeClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (util.dom.hasClassName(el, cName)) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
el.className = util.trim(el.className.replace(re, ''));
}
}
/* Remove leading and trailing whitespace and reduce
** multiple intermediate whitespaces to a single space
*/
util.trim = function(s) {
return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}
Change the listeners so they passes a reference to the clicked button:
<button id="btn1" onclick="change(this)">1</button>
Now when a button is clicked you can do:
function change(target) {
var el = document.querySelector('button.selectedButton');
if (el) util.dom.removeClassName(el, 'selectedButton');
util.dom.addClassName(target, 'selectedButton');
}
It would be better to put a single listener on a parent element and use the related event's target property to find the button that was clicked. Also, you can remember the last button that the class was added to so you don't have to search for it next time. But that won't work if you are setting a selected button at the server.
Related
I am trying to reset all the background colours when I click on one button and change the colour of the selected button. I want in the beginning for one button to have the background colour of dark grey as shown in the snippet, and when I click on another button all of the buttons would be resetted back to white and the clicked button will turn dark grey. How can I achieve this?
Right now when I click on another button nothing happens.
This is my code, what is wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/* Style the buttons */
.portfolio-buttons {
border: none;
outline: none;
padding: 12px 16px;
/* background-color: white; */
cursor: pointer;
}
.portfolio-buttons-normal {
background-color: white;
}
.portfolio-buttons:hover {
background-color: #ddd;
}
.portfolio-buttons-active {
background-color: #666;
color: white;
}
</style>
</head>
<body>
<div id="myBtnContainer">
<button class="portfolio-buttons portfolio-buttons-normal portfolio-buttons-active">Show
all</button>
<button class="portfolio-buttons portfolio-buttons-normal" >.html</button>
<button class="portfolio-buttons portfolio-buttons-normal">.css</button>
<button class="portfolio-buttons portfolio-buttons-normal" >.js</button>
<button class="portfolio-buttons portfolio-buttons-normal" >.java</button>
<button class="portfolio-buttons portfolio-buttons-normal" >.py</button>
</div>
<script>
function changeClass(button, classRef) {
button.classList.forEach((className) => {
if (className.startsWith("portfolio-buttons-active")) button.classList.remove(className);
});
console.log(classRef);
button[classRef].classList.add("portfolio-buttons-active");
}
document.querySelectorAll("portfolio-buttons").forEach((button, buttonNum) => {
button.addEventListener("click", function () {
document.querySelectorAll(".portfolio-buttons-normal").forEach((item) => {
changeClass(item, buttonNum);
console.log(buttonNum);
});
});
});
</script>
</body>
</html>
You are over-complicating it :) You are setting up your click listener correctly, but you just need 2 simple steps inside the listener:
1. Reset the current active button: simply get all buttons with the active class (we don't care about the rest, so no need to process them!) and remove it:
document.querySelectorAll(".portfolio-buttons-active").forEach((button) => {
button.classList.remove("portfolio-buttons-active");
});
2. Set the clicked button to active: your click handler is added to the button so we when that button is clicked button, add the active class to it:
button.classList.add("portfolio-buttons-active");
That's it! Putting this together all you need is the following:
document.querySelectorAll(".portfolio-buttons").forEach((button) => {
button.addEventListener("click", function() {
// Reset the currently active buttons:
document.querySelectorAll(".portfolio-buttons-active").forEach((button) => {
button.classList.remove("portfolio-buttons-active");
});
// Add the active class to the clicked button
button.classList.add("portfolio-buttons-active");
});
});
Working Example: I've put steps 1 and 2 into functions in this code, in case you need to add more functionality in each step later
/* Add the active class to the button passed in */
function setThisButtonActive(button) {
button.classList.add("portfolio-buttons-active");
}
/* select all active buttons, and remove the active class from them */
function resetActiveButton() {
document.querySelectorAll(".portfolio-buttons-active").forEach((button) => {
button.classList.remove("portfolio-buttons-active");
});
}
document.querySelectorAll(".portfolio-buttons").forEach((button) => {
button.addEventListener("click", function() {
resetActiveButton();
setThisButtonActive(button);
});
});
/* Style the buttons */
.portfolio-buttons {
border: none;
outline: none;
padding: 12px 16px;
/* background-color: white; */
cursor: pointer;
}
.portfolio-buttons-normal {
background-color: white;
}
.portfolio-buttons:hover {
background-color: #ddd;
}
.portfolio-buttons-active {
background-color: #666;
color: white;
}
<div id="myBtnContainer">
<button class="portfolio-buttons portfolio-buttons-normal portfolio-buttons-active">Show
all</button>
<button class="portfolio-buttons portfolio-buttons-normal">.html</button>
<button class="portfolio-buttons portfolio-buttons-normal">.css</button>
<button class="portfolio-buttons portfolio-buttons-normal">.js</button>
<button class="portfolio-buttons portfolio-buttons-normal">.java</button>
<button class="portfolio-buttons portfolio-buttons-normal">.py</button>
</div>
You are missing a . in the querySelectorAll where you select the buttons. So it's looking for the element portfolio-buttons instead of the class.
The classList interface has a contains method which checks if a class is present on an element. So there is no need to loop and check the className string. Also there is no need at all, if the class is not on the element nothing is removed.
For the reset button, give it a way to identify it's uniqueness. In the example above I gave it a value attribute with a string in it. When clicking check the if it is the reset button that is clicked and simply don't add a new active class.
const buttons = document.querySelectorAll(".portfolio-buttons");
buttons.forEach((button) => {
button.addEventListener('click', event => {
buttons.forEach(button => button.classList.remove('portfolio-buttons-active'));
if (button.value !== 'reset') {
button.classList.add('portfolio-buttons-active');
}
});
});
/* Style the buttons */
.portfolio-buttons {
border: none;
outline: none;
padding: 12px 16px;
/* background-color: white; */
cursor: pointer;
}
.portfolio-buttons-normal {
background-color: white;
}
.portfolio-buttons:hover {
background-color: #ddd;
}
.portfolio-buttons-active {
background-color: #666;
color: white;
}
<div id="myBtnContainer">
<button class="portfolio-buttons portfolio-buttons-normal portfolio-buttons-active" value="reset">Show all</button>
<button class="portfolio-buttons portfolio-buttons-normal">.html</button>
<button class="portfolio-buttons portfolio-buttons-normal">.css</button>
<button class="portfolio-buttons portfolio-buttons-normal">.js</button>
<button class="portfolio-buttons portfolio-buttons-normal">.java</button>
<button class="portfolio-buttons portfolio-buttons-normal">.py</button>
</div>
You could simplify it by checking e.target:
const buttons = document.querySelectorAll(".portfolio-buttons");
buttons.forEach(button => {
button.addEventListener("click", function(e) {
e.target.classList.add('portfolio-buttons-active');
buttons.forEach(item => {
if (item !== e.target) {
item.classList.remove('portfolio-buttons-active');
}
});
});
});
.portfolio-buttons {
border: none;
outline: none;
padding: 12px 16px;
/* background-color: white; */
cursor: pointer;
}
.portfolio-buttons-normal {
background-color: white;
}
.portfolio-buttons:hover {
background-color: #ddd;
}
.portfolio-buttons-active {
background-color: #666;
color: white;
}
<div id="myBtnContainer">
<button class="portfolio-buttons portfolio-buttons-normal portfolio-buttons-active">Show
all</button>
<button class="portfolio-buttons portfolio-buttons-normal">.html</button>
<button class="portfolio-buttons portfolio-buttons-normal">.css</button>
<button class="portfolio-buttons portfolio-buttons-normal">.js</button>
<button class="portfolio-buttons portfolio-buttons-normal">.java</button>
<button class="portfolio-buttons portfolio-buttons-normal">.py</button>
</div>
If e.target isn't the current element in the loop, then remove the active class, otherwise, add the active class.
I'm currently having some trouble automatically sorting buttons alphabetically. I can't figure out how to sort these buttons (jquery/javascript), but I want to do it automatically, when the page loads. Thanks for the help. Here's my code:
<style>
.games-button {
background-color: #383838;
color: #eeeeee;
text-align: middle;
text-decoration: none;
font-size: 14px;
cursor: pointer;
border-radius: 5px;
height:42px;
vertical-align: left;
display: inline-block;
letter-spacing: 0.5px;
float: left;
overflow:hidden;
margin-left:100px;
margin-bottom: 2px;
text-transform: uppercase;
}
.games-button:hover {
box-shadow: inset 0 0 100px 100px rgba(255, 255, 255, 0.1);
}
</style>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">A</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">Z</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">H</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">B</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">N</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">C</button>
Update:
This is a code I have that sorts the buttons on click of a button. How can I do this without a button?
<button onclick="sortList()">Sort</button>
<ul id="id01">
<button>z</button>
<button>a</button>
<button>b</button>
<button>l</button>
<button>b</button>
</ul>
<script>
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("id01");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("button");
for (i = 0; i < (b.length - 1); i++) {
shouldSwitch = false;
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
</script>
It seems that you're getting into js development. Good luck with that.
In order to manipulate DOM elements, it's always easier if you put in some trails or hints to help your code find your elements.
In this case, all of your buttons are placed in the body element, so to make it easier to locate and replace the buttons, place them inside another element. Like so:
<div id="button-container">
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">A</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">Z</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">H</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">B</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">N</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">C</button>
</div>
Then locate them and sort them.
<script>
'use strict';
const buttonContainer = document.getElementById('button-container');
const sortedButtons = [... buttonContainer.children].sort((buttonA, buttonB) => {
const name1 = buttonA.innerText.toLowerCase();
const name2 = buttonB.innerText.toLowerCase();
if(name1 === name2){
return 0;
} else if(name1 < name2){
return -1;
} else {
return 0;
}
});
sortedButtons.forEach(button => buttonContainer.append(button));
</script>
That's it.
I am trying to create a text font colour drop down button where it gives you an option of multiple colour to pick from and then it would change the colour of the text. I am not sure on how to approach this and I am not meant to use jQuery. Any help would be appreciated. In the code below it shows other examples of other button where they change the user input entered into the contenteditable. I want the font colour button to do the same but just change the colour of the text
const TAB_KEY = 9;
const ENTER_KEY = 13;
const SHIFT_KEY = 16
const editor = document.querySelector('.editor');
editor.appendChild(document.createElement('li'));
editor.addEventListener('keydown', (e) => {
let code = e.keyCode || e.which;
if (code == TAB_KEY) {
e.preventDefault();
let parent = e.target;
let ul = document.createElement('ul');
let li = document.createElement('li');
ul.appendChild(li);
parent.appendChild(ul);
moveCursorToEnd(li);
} else if (code == ENTER_KEY) {
e.preventDefault();
let parent = e.target;
let li = document.createElement('li');
parent.appendChild(li);
moveCursorToEnd(li);
} else if (code == TAB_KEY * TAB_KEY){
e.preventDefault();
let parent = e.target;
let ol = document.createElement('ol');
let li = document.createElement('li');
ol.appendChild(li);
parent.appendChild(ol);
moveCursorToEnd(li);
}
});
function moveCursorToEnd(el) {
el.focus();
document.execCommand('selectAll', false, null);
document.getSelection().collapseToEnd();
}
/*editor.addEventListener('click', (x) => {
x = document.getElementById("b");
if(x.style.fontWeight == "bolder"){
x.style.fontWeight = "normal";
} else {
x.style.fontWeight = "bolder";
}
});*/
function bold(){
if(document.execCommand("bold")){
document.execCommand("normal");
}else{
document.execCommand("bold");
}
}
/*function underline(){
let x = document.getElementById("text");
if(x.style.textDecoration == "underline"){
x.style.textDecoration = "none";
}else{
x.style.textDecoration = "underline";
}
}*/
function underline(){
if(document.execCommand("underline")){
document.execCommand("none");
}else{
document.execCommand("underline");
}
}
/*Turns the font of the text to Italic*/
function italic(){
if(document.execCommand("italic")){
document.execCommand("normal");
}else{
document.execCommand("italic");
}
}
function highlighSelectedText(){
let sel = window.getSelection().getRangeAt(0);
let selText = sel.extractContents();
let span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selText);
sel.insertNode(span);
}
/*function printPage(){
let printButton = document.getElementById("ul");
printButton.style.visibility = 'hidden';
window.print();
printButton.style.visibility = 'visible';
}*/
body{
margin-top:1em;
margin-bottom: 10em;
margin-right: 1em;
margin-left: 1em;
border: solid;
border-color: #0033cc;
background-color: #f6f6f6;
}
div button{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div input{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div{
list-style-type:square;
list-style-position: inside;
margin-left: 0.25em;
margin-bottom: 5em;
}
section {
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
.editor {
font-weight: normal;
}
div contenteditable{
margin-bottom: 10em;
}
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<head>
<title>Outliner</title>
<link href="style.css" rel="stylesheet" title="Style">
<div>
<button id="b" onclick="bold()"> B </button>
<button onclick="underline()"> U </button>
<button onclick="italic()"> I </button>
<input type="button" onclick="highlighSelectedText()" value="Highlight"/>
<div id="text" class="editor" contenteditable="true" draggable="true"></div>
</div>
<section>
<input id="saveAs"></input>
<button onclick="saveTextFile()">Download</button>
<input type="file" id="load"/>
<button onclick="loadFile()">Load</button>
</section>
<section>
<button class="btn btn-primary" onclick="saveChanges()">Save Text</button>
<button class="btn btn-warning" onclick="clearStorage()">Reset</button>
</section>
</head>
<script type= "text/javascript" src='setting.js'></script>
</body>
First off we will use a CSS variable. Lets declare a value at :root
:root {
--font-color: #000;
}
Now we will use that value to style the font color of our P tags.
p {
color: var(--font-color);
}
Now when somebody clicks one of the color names, we want to change the value of --font-color. (Notice we are using the data- attribute model to store the color we want to change too).
document.documentElement.style.setProperty('--font-color', target.dataset.color);
And presto we can now change color easily. This works for other values also.
Here is a great article
document.addEventListener('click', ({ target }) => {
if(target.matches('p')) {
document.documentElement.style.setProperty('--font-color', target.dataset.color);
}
});
:root {
--font-color: #000;
}
p {
width: 30%;
border: 2px solid #00000030;
border-radius: 7px;
margin: 0.25rem;
padding: 0.25rem;
color: var(--font-color);
}
<h2>Click a color</h2>
<p data-color="#f00">Red</p>
<p data-color="#0f0">Green</p>
<p data-color="#00f">Blue</p>
<p data-color="#000">Reset</p>
You can manipulate the style variable:
<div id="text">
Choose a color
</div>
<input id="color" type="color">
<button onclick="document.getElementById('text').style.color = document.getElementById('color').value;">Change Color</button>
I have two buttons. When one is clicked, I want it to turn from gray to black and stay black unless the page is refreshed or the other button is clicked. If the other button is clicked, I would like it to turn black and for the first one to go back to gray. I assume JS is the best way for this, but I'm not sure how to do it.
Here is some of my code below:
HTML:
<a id="button"></a>
<a id="button"></a>
CSS:
#button {
display:inline-block;
height:10px;
width:10px;
border-radius:10px;
background-color:gray;
}
Many thanks in advance.
ID names should not be reused, change them to a class name instead, but they will still need an unique ID name each for us to apply Javascript logic to them.
html:
<a id="button1" class="button"></a>
<a id="button2" class="button"></a>
css:
.button
{
display:inline-block;
height:10px;
width:10px;
border-radius:10px;
}
Javascript:
document.getElementById("button1").style.backgroundColor ="gray";
document.getElementById("button2").style.backgroundColor ="gray";
document.getElementById("button1").onclick = function(){
this.style.backgroundColor ="black";
document.getElementById("button2").style.backgroundColor ="gray";
};
document.getElementById("button2").onclick = function(){
this.style.backgroundColor ="black";
document.getElementById("button1").style.backgroundColor ="gray";
};
Here's an example I whipped up with no JavaScript - instead I'm using two radio buttons that are styled depending on which one is "checked".
http://codepen.io/capitalq/pen/gLWLMK
.button {
-webkit-appearance: none;
appearance: none;
border: 0;
background: gray;
height: 50px;
width: 50px;
margin: 10px;
outline: none;
display: inline-block;
border-radius: 50%;
}
.button:checked {
background: black;
}
<input type="radio" class="button" name="buttons" id="button1" />
<input type="radio" class="button" name="buttons" id="button2" />
Use the jquery addClass function to add a class with a set background.
The class will remain until there is a page load.
CSS Only aproach is :active, but it will not work on buttons, because the active property fades away once you release the click button. Maybe using an tag disguised as button may work, but will fade away once it losses the active state.
With jQuery you can do it quite easily.
$('#buttons .item').on("click",function(){
$("#buttons .item.active").removeClass('active');
$(this).addClass("active");
});
button{
color: white;
}
.item{
background-color: gray;
}
.active{
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
<button class="item">Button 1</button>
<button class="item">Button 2</button>
<button class="item">Button 3</button>
</div>
<style media="screen">
#buttonA, #buttonB {
display: inline-block;
height: 10px;
width: 10px;
border-radius: 10px;
background-color: gray;
}
</style>
<a id="buttonA"></a>
<a id="buttonB"></a>
<script type="text/javascript">
var buttonA = document.querySelector('#buttonA');
var buttonB = document.querySelector('#buttonB');
var changeColour = function (e) {
if (e.target === buttonA) {
buttonA.style.backgroundColor = 'black';
buttonB.style.backgroundColor = 'gray';
}
if (e.target === buttonB) {
buttonB.style.backgroundColor = 'black';
buttonA.style.backgroundColor = 'gray';
}
};
buttonA.addEventListener('click', changeColour, false);
buttonB.addEventListener('click', changeColour, false);
</script>
There is an HTML button element. So if you want to mark up a button on your page, you really ought to use:
<button type="button"></button>
Here is an approach using <button> and classList in javascript:
var buttons = document.getElementsByTagName('button');
function paintItBlack() {
for (var i = 0; i < buttons.length; i++) {
buttons[i].classList.remove('clicked');
}
this.classList.add('clicked');
}
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click',paintItBlack,false);
}
.clicked {
color: rgb(255,255,255);
background-color: rgb(0,0,0);
}
<button type="button">Button A</button>
<button type="button">Button B</button>
JavaScript is unnecessary at this time. Use this code in your .css file or in the "style" tag on the html file.. It will be black when the mouse is over it and after you click.
a:hover
{
background-color:black;
}
a:target
{
background-color:black;
}
i want my button to change color on click [suppose black],but on page refresh i dont want it to change its color back to original color.
<html>
<head>
<style>
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>CSS Buttons</h2>
<input type="button" class="button" value="Input Button">
</body>
</html>
<html>
<head>
<script>
/* On load of the page we are calling this function which will
give us the color name stored in our local storage */
function changeColor() {
var color = localStorage.getItem("colorName");
document.getElementById("color").style.backgroundColor = color;
}
/*This function will change the color of button on click*/
var i = -1;
function colorArray() {
var arr = new Array();
arr[0] = "Red";
arr[1] = "Orange";
arr[2] = "Green";
arr[3] = "Blue";
i++;
if (i > arr.length - 1) {
i = 0;
}
/* We have an array with the color names, you can add any
number of colors in this array */
/* After fetching the color from array we are storing
it in the local storage of our browser for future use*/
localStorage.setItem("colorName", arr[i]);
document.getElementById("color").style.backgroundColor = arr[i];
}
</script>
</head>
<body onload="changeColor()">
<button onclick="colorArray()" id="color"> Change Color </button>
</body>
</html>
Click here for Live Demo and complete source code
You can use local storage to preserve the color after the page refresh.
window.onload = function(){
var btn = document.getElementById("btn");
if(localStorage["bg-color"]){
btn.style.backgroundColor = localStorage.getItem("bg-color");
};
btn.onclick = function(){
if(!localStorage["bg-color"]){
localStorage.setItem("bg-color", "yellow");
};
btn.style.backgroundColor = localStorage.getItem("bg-color");
};
// remove from storage localStorage.removeItem("bg-color")
};
When you get an element with JavaScript, you can access a bunch of properties of this element.
There is two solutions to modify his properties :
modify the css property (myElement.style.myProperty = 'myNewValue')
modify the class list (myElement.classList.add('myClassName'))
Update after author edit :
You could call a function onclick="..." on the button.
The function will add a class to this button to change his style.
Then store on your localStorage, or on a session, or on a cookie or in your database the state of the button with a boolean (clicked = true for example).
Next time you visit the page, add a check onload to add this class on this button if clicked == true.
You could use cookies to store the state of the color between page reloads, here is a basic example.
function setColor(color){
document.querySelector('#button').style.background = color
document.cookie = `color=${color};`
}
function getColor() {
return document.cookie.split('; ') // ['color=blue']
.reduce((acc, x) => {
const [ key, value ] = x.split('=') // ['color', 'blue']
acc[key] = value // { color: 'blue' }
return acc
})
.color
}
// run the functions on page load
window.addEventLister('DOMContentLoaded', function(){
setColor(getColor())
})
setColor('#bada55')
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
<h2>CSS Buttons</h2>
<input id="button" type="button" class="button" value="Input Button">