Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript: Toggling from true to false works but false to true doesnt

I want to toggle the div’s attribute but toggle works only from True to false;

<div class="thisDiv" isshown="true">
  click here
</div>
let div = document.querySelector(".thisDiv")

div.addEventListener("click", function(){
    var isShown = div.getAttribute("isshown");
    
    isShown = !isShown;
    div.setAttribute("isshown", isShown);
})

here is the fiddle code I made:
https://jsfiddle.net/tm57kadf/5/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Attributes are strings, so you need to decide what is true and false. I usually set '1' for true, and an empty string for false. Here is your code, fixed:

let div = document.querySelector(".thisDiv")

div.addEventListener("click", function(){
  console.log("")
  var isShown = div.getAttribute("isshown") ? true : false;
    
  console.log(`before: ${isShown}`)
  isShown = !isShown;
  div.setAttribute("isshown", isShown ? '1' : '');
    
  console.log(`after: ${isShown}`)
})
<div class="thisDiv" isshown="true">
  click here
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading