Luiz Cruz Luiz Cruz - 1 year ago 85
HTML Question

JQuery - Begginner Issue with Conditional

I'm having trouble making the following conditional revert the elements to its default CSS if it's false.

What the function does is animate some elements CSS beyond a certain point in scroll (specifically when those element's container - a fixed navbar - is scrolled above another div).

The function Works correctly when I scroll down but if I go back (if the variable offsetDiv > offsetNav) it doesn't "revert" to the defaults as I wanted it to. What's the issue here, please?


var offsetDiv = $('div').offset().top;
var offsetNav = $('nav').offset().top;

if (offsetDiv <= offsetNav){
else {
$('nav>ul>li>a').animate({lineHeight:"140px"},200); // These are "CSS defaults". I put them here again because I thought the condition being false would trigger this.


nav {position:fixed};
#logosmall {width:140px;height:140px};
nav>ul>li>a {line-height:140px;};

Answer Source

As this jsFiddle shows, your annimations do appear to be applied when you want them to. (watch the console output in the fiddle)

I think part of your problem is that you cant animate things like background-color with .animate()

If you wan't to animate background color, you'll need to use something like jQuery UI. Good news is, if you're willing to use jQuery UI, you can use .switchClass() to make this all a cinch like this:


$(document).ready(function() {
  $(window).scroll(function() {
    var $nav = $('.my-nav')
    var $logo = $('.logosmall')
    var $link = $('.link')
    var offsetDiv = $("#white").offset().top;
    var offsetNav = $link.offset().top;
    if (offsetDiv <= offsetNav) {
      $nav.switchClass('up', 'down', 400);
      $logo.switchClass('up', 'down', 400);
      $link.switchClass('up', 'down', 400);
    } else {
      $nav.switchClass('down', 'up', 400);
      $logo.switchClass('down', 'up', 400);
      $link.switchClass('down', 'up', 400);
.my-nav.up {
  position: fixed;
  color: black;
  width: 100%;
  border-top: 20px solid green;

.my-nav.down {
  position: fixed;
  color: black;
  width: 100%;
  border-top: 0px;
  background-color: orange;

.logosmall.up {
  height: 140px;
  width: 140px;
  float: left;
  background-color: yellow;

.logosmall.down {
  height: 100px;
  width: 100px;
  float: left;
  background-color: yellow;

.link.up {
  line-height: 140px;
  font-size: 14pt;

.link.down {
  line-height: 80px;
  font-size: 10pt;

nav ul {
  float: right;
  margin-right: 50px;

nav ul li {
  float: left;

div#heroimage {
  background-color: red;
  width: 100%;
  height: 600px;

div#white {
  background-color: #fff;
  width: 100%;
  height: 1000px;
<script src=""></script>
<script src=""></script>
<nav class="my-nav up">
  <div class="logosmall up"></div>
    <li><a class="link up">Link 1</a></li>
<div id="heroimage"></div>
<div id="white"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download