0

Is it possible to do this without using JQuery?

I would like a div to change its shadow color once I clicked on it, and when I click on it again it will change back to its original color. Here's the code: http://jsfiddle.net/kqv7x5f8/5/

var btn = document.getElementById("btn");

function toShadow() {
  document.getElementById("btn").style.boxShadow = "5px 5px red"
}
#btn {
  height: 20px;
  border: 2px solid black;
  box-shadow: 5px 5px black;
}
<div id="btn" onclick="toShadow">
  click to change shadow; click again to change back
</div>

Thank you!

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49

2 Answers2

4

It is better in this case to toggle a class by using classList.toggle()

const button = document.getElementById('btn');

button.addEventListener('click', e => e.currentTarget.classList.toggle('shadow'));
#btn {
  height: 20px;
  border: 2px solid black;
}

.shadow {
  box-shadow: 5px 5px black;
}
<div id="btn">
  click to change shadow; click again to change back
</div>
dippas
  • 58,591
  • 15
  • 114
  • 126
  • Thank you! I have a follow-up question: instead of toggling the class when clicking on the div, how to toggle it when clicking anywhere else on the screen? – Chris Nalusaku Jun 27 '22 at 22:00
  • 1
    See this https://stackoverflow.com/questions/36695438/detect-click-outside-div-using-javascript – dippas Jun 27 '22 at 22:01
0

You can make use of a boolean with an if/else statement for this problem

var btn = document.getElementById("btn");
var isRed = false;

function toShadow(){
if(isRed){
btn.style.boxShadow ="5px 5px black"
isRed = false;
}
else {
btn.style.boxShadow ="5px 5px red"
isRed = true;
}
}
Tikster
  • 31
  • 2
  • 3