Is it possible to change the background color and go back to the original in simple javascript every time I click a button?

I don't see any results on google unless I'm using jQuery and I'm not sure if jQuery and javascript work together.

0


source to share


2 answers


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());" />
      

Run codeHide result


0


source


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} 
});

      

0


source







All Articles