Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Scroll detection fire once

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' : '');
    });
  });
});
like image 808
AviateX14 Avatar asked Oct 04 '12 16:10

AviateX14


2 Answers

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

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

like image 126
ilan berci Avatar answered Nov 19 '22 06:11

ilan berci


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;
   } 
});
like image 4
GajendraSinghParihar Avatar answered Nov 19 '22 05:11

GajendraSinghParihar