Trying to do a CSS Transition on a class change
CssCss Problem Overview
Was wondering if there was a way to do a css transition when div is given a certain class. My best example is this site http://ideaware.co/
When you scroll down and the header becomes fixed, it does a background color change and has opacity. Really nice looking.
I am working on a template I have here http://www.niviholdings.com/collide/ and what I want to do is when the < nav > becomes fixed, I want the < ul > to slide over to the right.
Hopefully I am explaining this correctly.
Css Solutions
Solution 1 - Css
> Was wondering if there was a way to do a css transition when div is > given a certain class.
Sure you can...
document.querySelector('#header').addEventListener('click', function(e) {
e.target.classList.toggle('transition');
})
#header {
background: red;
padding: 10px 0;
position: relative;
-webkit-transition: all 1s linear;
-moz-transition: all 1s linear;
-o-transition: all 1s linear;
transition: all 1s linear;
left:0;
}
#header.transition {
background: green;
left: 50px;
}
<div id="header">Click me to toggle class</div>
Solution 2 - Css
2 points i found that may help:
Transitions from auto
to a fixed value might be a problem. Eventually you could try setting the margin-left
of the .main-nav-ul
to a fixed value per default, not only when it's sticky.
The second is (and this is hacky). Try to apply the class for your .main-nav-ul
delayed:
setTimeout(function() {
$('.main-nav-ul').addClass('nav-slide'); // line 57 in jquery.sticky.js
}, 100);
Solution 3 - Css
CSS Transitions in 4 easy steps
-
Make sure that what you want to do is possible with CSS transitions. You can do that by checking the W3C docs.
-
Add the transition, and your starting style, to your base element.
-
Add a class or state that has styles that have changed.
-
Add a mechanism to add the class (if applicable).
Quick example, let's say you want to animate a margin change on :hover
. You'd just do this:
element {
margin-left: 10px;
transition: margin-left linear .5s;
}
element:hover {
margin-left: 0;
}