1

How do I get a CSS transition to work on my JS action ?

My JS displays or does not display depending if clicked.

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("hamburger-icon").style.display = "none";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("hamburger-icon").style.display = "block";
}
#hamburger-icon {
    font-size:30px;
    cursor:pointer;
    background: green;
    display: block;
    transition: 0.5s;
}
<div class="row">
    <span class="col-3" id="hamburger-icon" style="float: left" onclick="openNav()">&#9776;</span>
    <p class="col-9" style="float: left">logo</p>
</div>

<div id="mySidenav" class="sidenav">
    <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
    <form class="navbar-form navbar-left">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Search">
        </div>
    </form>
</div>
Arkellys
  • 5,562
  • 2
  • 16
  • 40
Beep
  • 2,737
  • 7
  • 36
  • 85
  • Unclear what you are asking - what do you want to transition, and what is the problem? Right now, you have only shown the `transition` property set for `#hamburger-icon`, but the only value you change on that element, `display`, is not transitionable. – misorude Oct 02 '18 at 10:32
  • @misorude sure I just want to apply a simple fade in or fade out effect to display non or display block – Beep Oct 02 '18 at 10:34
  • 1
    Only that isn’t “simple” to begin with, because, again, `display` is not transitionable. So you will need to replace it with something else - like a transition of the opacity. And if you really need to have `display:none` set at the end, then you will have to add a handler for the transitionend event. Perhaps do some research first, you’re likely not the first to try something like this. – misorude Oct 02 '18 at 10:38
  • Thanks I did not know display was not able to have a transition, now I know why my google search was not returning the answer. +1 this helped me solve the problem – Beep Oct 02 '18 at 10:55

1 Answers1

0

Triggering transitions

You can trigger CSS transitions directly with pseudo classes like :hover (activates when mouse goes over an element), :focus (activates when a user tabs onto an element, or when a user clicks into an input element), or :active (activates when user clicks on the element).

https://codepen.io/zellwk/pen/Qqzzxd

.button {
  background-color: #33ae74;
  transition: background-color 0.5s ease-out;
}

.button:hover {
  background-color: #1ce;
}

You can also trigger CSS transitions through JavaScript by adding or removing a class.

https://codepen.io/zellwk/pen/GMPPBg

Adapted from : https://zellwk.com/blog/css-transitions/

Dehan
  • 4,818
  • 1
  • 27
  • 38