Home > Enterprise >  javascript: Toggling from true to false works but false to true doesnt
javascript: Toggling from true to false works but false to true doesnt

Time:01-29

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

<div  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/

CodePudding user response:

getAttribute returns a string. A non-empty string is truthy value so adding a NOT(!) operator converts it into false but not the other way around.

CodePudding user response:

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  isshown="true">
  click here
</div>

  • Related