Jon
Jon

Reputation: 29

JQuery Offset Script

I am creating a navigation menu for a website. When the user scrolls past the point 497px it needs to change colour. I have wrote this script:

$(document).ready(function(){

    function checkOffset() {
      var offset = $(document).scrollTop();
      console.log(offset);
        if(offset > 497){
          $("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000);
          $("#fixedBar nav a").animate({color: '#FFF'}, 1000);
        }else{
          $("#fixedBar").animate({backgroundColor: '#FFF'}, 1000);
          $("nav a").animate({color: '#1B1B1B'}, 1000);

        }
      }
    $(window).scroll(function() { 
      checkOffset();
     });

  });

If I refresh the page and it is past that point then it indeed changes, however if I simply scroll past that point then it doesn't change. How can I fix this?

Upvotes: 2

Views: 88

Answers (3)

kosmos
kosmos

Reputation: 4288

To use .animate() with colors, you will need jQueryUI. So, add the framework to your head:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js""></script>

Then, try it again (I modified a little your current code):

$(function(){
    $(window).on('scroll', function() { 
        checkOffset();
    });
});

function checkOffset() {
    var $target = $('#fixedBar');
    var offset = $(window).scrollTop();
    console.log(offset);
    if(offset >= 10){
        $target.stop(true, false).animate({ 'background-color': 'green'}, 1000);
        //$("#fixedBar nav a").animate({color: '#FFF'}, 1000);
    }
    else if( offset < 10 ){
        $target.stop(true, false).animate({ 'background-color': 'blue' }, 1000);
        //$("nav a").animate({color: '#1B1B1B'}, 1000);
    }
}

Check the jsFiddle.

Upvotes: 1

Vinod Kumar
Vinod Kumar

Reputation: 981

Your script probably works.

But since you are animating on every scroll. there is a chance of having consecutive animation cycles.

Possible solutions would be (Any one of these points),

  1. To use either css method rather than animate
  2. Executing stop() before animating should help.
  3. Check the existing color value before executing the animate method

To know more about stop() in jQuery.

Upvotes: 1

IonDen
IonDen

Reputation: 773

You should call checkOffset(); one more time:

$(document).ready(function(){

    function checkOffset() {
        var offset = $(document).scrollTop();
        console.log(offset);
        if(offset > 497){
            $("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000);
            $("#fixedBar nav a").animate({color: '#FFF'}, 1000);
        } else {
            $("#fixedBar").animate({backgroundColor: '#FFF'}, 1000);
            $("nav a").animate({color: '#1B1B1B'}, 1000);  
        }
    }
    $(window).scroll(function() { 
        checkOffset();
    });

    checkOffset(); // <-- HERE

});

Upvotes: 0

Related Questions