0

I am trying to set the visibility of a div element to visible or hidden depending on the previous state. i.e, I am trying to set the visibility to hidden when the element was previously visible and vice versa with an on click event.

html:

<div id="cartwin"></div>

css:

#cartwin {

position: fixed;
z-index: 9999;
right: 0%;
top: 7%;
background-color: black;
border: 1px solid white;
border-radius: 5px;
height: 40%;
width: 25%;
visibility: hidden;
}

js:

cart.onclick = function togglecart() {

    const cart = document.getElementById('cartwin').style.visibility;


    if (cart == 'visible') {

        cart = 'hidden';

    }

    else if (cart == 'hidden') {

        cart = 'visible';

    }

}

This code has no effect at all, and I am inclined to believe it has to do with my if tests after a bit of looking around, but i could not find anything out.

Ken
  • 65
  • 8

1 Answers1

1

You will have to use window.getComputedStyle

See comment inside the code and check the console when clicking

var cart = document.querySelector('.cart');
var cartwin = document.getElementById('cartwin')

cart.onclick = function togglecart() {

    var style = window.getComputedStyle(cartwin);

    console.log(style.visibility);

    // use style.visibility
    // this is an option now you can handle 
    // what you have started with in your question
    // and move on from here with rest of your code

    // BUT before you do so, see the next snippet
    // on how much simpler you could achieve what I believe you are trying

}
#cartwin {

position: fixed;
z-index: 9999;
right: 0%;
top: 7%;
background-color: black;
border: 1px solid white;
border-radius: 5px;
height: 40%;
width: 25%;
visibility: hidden;
}
<div class="cart">click on cart here</div>
<div id="cartwin">
  <h4>lots of products in my cart</h4>
</div>

Above example is to fix the problem your were facing and showing a possible solution to it, but ...

Consider this snippet as a better solution Here you will not handle the styles with javascript but just add/remove a class via javascript.

var cart = document.querySelector('.cart');
var cartwin = document.getElementById('cartwin')

cart.onclick = function togglecart() {

    // handle the logic here in javascript
    // but keep the styles where they belong => CSS
    // all you need to do here is "toggle" a class name
    cartwin.classList.toggle('active');

}
#cartwin {

position: fixed;
z-index: 9999;
right: 0%;
top: 7%;
background-color: black;
border: 1px solid white;
border-radius: 5px;
height: 40%;
width: 25%;
visibility: hidden;
}

#cartwin.active {
    visibility: visible;
}
<div class="cart">click on cart here</div>
<div id="cartwin">
  <h4>lots of products in my cart</h4>
</div>
caramba
  • 21,963
  • 19
  • 86
  • 127