Michael Rogers
Michael Rogers

Reputation: 1

Javascript to make a button take multiple action on an element

I currently have buttons that adjust the height, color, opacity of a box for example-

document.getelementbyID("growbutton").addEventlistener("click", function growFunction() {
  document.getelementbyID("box").style.height = "300px"
});

document.getelementbyID("bluebutton").addEventlistener("click", function blueFunction() {
  document.getelementbyID("box").style.color = "#0000FF"
});

Those work fine- What I want is a reset button, that will reset "box" back to original settings. Current JS looks like this.

document.getelementbyID("resetbutton").addEventlistener("click", function resetFunction() {
  document.getelementbyID("box").style.height = "150px"
});

document.getelementbyID("resetbutton").addEventlistener("click", function resetFunction() {
  document.getelementbyID("box").style.color = "#FFA500"
});

When executed however, the "box" only resets in height, but does not reset in color. Any help would be greatly appreciated.

Upvotes: 0

Views: 867

Answers (3)

Michael Rogers
Michael Rogers

Reputation: 1

Ya'll are going to be really mad at me... Super noob mistake. The reset function would've been working this whole time with all of the JS that was posted. My color change button address backgroundcolor, my reset addresses color. It's fixed now!

Upvotes: 0

iagowp
iagowp

Reputation: 2494

You don't need to send a single action per function. You can create a function resetFunction and pass it to addEventListener.

function resetFunction(){
  let box = document.getElementById("box");
  box.style.height = "150px";
  box.style.color = "#FFA500";
}

document.getElementById("resetbutton").addEventlistener("click", resetFunction);

This is the best way, but probably changing the name of your second function to resetFunction2 would also work

Upvotes: 1

Kinglish
Kinglish

Reputation: 23654

In effect you'll need to store a set of default values that you can refer to. You can do this when the document loads, ie:

<head>
<script>
var defaults = {}
function setDefaults() {
  defaults.box = {
    height: document.getElementByID("box").style.height,
    color: document.getElementByID("box").style.color
  }

// I tucked these functions in here since they need to fire after the page loads

    document.getElementByID("resetbutton").addEventListener("click", function resetFunction() {
      document.getElementByID("box").style.height = defaults.box.height
      document.getElementByID("box").style.color = defaults.box.color
    });


}
</head>
<body onload='setDefaults()'>
...

Upvotes: 0

Related Questions