Is it possible to change the background color and go back to the original in simple javascript every time I click a button?
Try using the attribute data-*
to keep the replacement color, the element's original background color, button
or initial
; JSON.parse()
, JSON.stringify()
, Array.prototype.reverse()
To switch the attribute values data-*
that set background
the element input type="button"
; onclick
event.
Undefined whether to switch background color or reset to original color once?
<input type="button" value="button" data-colors='["blue", "buttonface"]' onclick="this.style.background = JSON.parse(this.dataset.colors)[0]; this.dataset.colors = JSON.stringify(JSON.parse(this.dataset.colors).reverse());" />
source to share
jQuery won't conflict with javascript, it's just a js library :) So you can use selector.css()
jquery or, in standard js, I think that's it (element).style.background = color
.
I recommend using jQuery. Here's a simple jQuery way:
$("#button").click(function(){
$("#tochange").css("background-color", "colorhex");
});
If you want to change the colors, you can add a variable, for example.
var x;
$("#button").click(function(){
if(x==0){
$("#tochange").css("background-color", "colorhex");
x= 1;
}
else{other way round}
});
source to share