5

I have a small piece of JQuery designed to collapse my header, change its dimensions, and then stick it to the side of the screen. It all works apart from one part, the height 'toggle' function fires every time the user scrolls, which gets really irritating.

Is there a way I can detect scroll only once OR toggle only once?

$(window).scroll(function () {
var width = $(document).width() - 205;
var height = $(document).height();
  $('#me').animate({
    marginLeft: width,
    width: '22px',
    height: 'toggle',
    borderLeftWidth: "10px",
    borderRightWidth: "10px"    
  }, 1000, function() {
    $("#me:first").css("margin-top","-90px");
    var div = $('#me');
    $('#me h1').css("font-size","30px");
    var start = $(div).offset().top;
    $(div).css("height", height);
    $.event.add(window, "scroll", function() {
        var p = $(window).scrollTop();
        $(div).css('position',((p)>start) ? 'fixed' : 'static');
        $(div).css('top',((p)>start) ? '0px' : '');
    });
  });
});
1
  • use a flag and set it true onect it fired Commented Oct 4, 2012 at 16:38

2 Answers 2

10

look at jquery's one() functionality http://api.jquery.com/one/

It will only fire once and then promptly remove itself..

Sign up to request clarification or add additional context in comments.

Comments

4

use a flag to check it is first time or not

var doHeightToggle=true;


$.event.add(window, "scroll", function() {
   if(doHeightToggle)
   {
        var p = $(window).scrollTop();
        $(div).css('position',((p)>start) ? 'fixed' : 'static');
        $(div).css('top',((p)>start) ? '0px' : '');
        doHeightToggle = false;
   } 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.