-2

I'm trying to run this script only once per session. Script is supposed to show a slide out popup once user scrolls down.

Here is the code that shows to slide out. But how do I make it only run once?

jQuery(window).scroll( function(){
var wwd = jQuery(window).width();
if( wwd > 999 ){
fixedHeader();  // fix header on page scroll
}
});

var fixedHeader = function(){
var hdrHt = jQuery('header.site-header').height();
var scrPos = jQuery(window).scrollTop();
var aBarHt = jQuery('#wpadminbar').height();
if( scrPos > (hdrHt+700) ){
jQuery('div.slide').one.css('display','block');
jQuery('div.slide-hidden').css('display','none');
}
else
{
jQuery('div.slide-hidden').css('display','block');
}
}

RUN ONCE - if user scrolls down 700px - show slide out. If user goes back to top and then scrolls down again - DO NOT run 2nd time. Run once pre page load.

Please help. I'm not a programmer - I tried to use .one() but no success ... i have now idea how or where to put it. Please show code example.

Thanks very much!

Levchik
  • 496
  • 1
  • 5
  • 19
  • is this complete function code? Try IIFE – gurvinder372 Jan 12 '16 at 17:20
  • When you say once per session, do you mean slide out only on the first page and stay out on other pages? – iCollect.it Ltd Jan 12 '16 at 17:21
  • @TrueBlueAussie - once per page load. Once user scrolls down 700 px - show slide out. if user goes back to top and then scrolls down again, do not run 2nd time. I updated OG post – Levchik Jan 12 '16 at 17:33
  • @gurvinder372 I updated OP with complete script – Levchik Jan 12 '16 at 17:33
  • Check this URL http://stackoverflow.com/questions/34672090/disable-a-javascript-function-after-it-runs/34672380. You can use any logic to disable the function once it is executed. – Narendra CM Jan 12 '16 at 17:42

1 Answers1

0

update this method as

var fixedHeader = function()
{
   var hdrHt = jQuery('header.site-header').height(); 
   var scrPos = jQuery(window).scrollTop();
   var aBarHt = jQuery('#wpadminbar').height();
   if( scrPos > (hdrHt+700) )
   {
      if ( $.trim( jQuery('div.slide').attr( "data-firsttime" ) ).length == 0 )
      {
         jQuery('div.slide').one.css('display','block');
         jQuery('div.slide').attr( "data-firsttime", "true" );
      }
      jQuery('div.slide-hidden').css('display','none');
   }
   else
   {
      jQuery('div.slide-hidden').css('display','block');
   }
}

basically set an attribute (any attribute 'data-firsttime' in this case) of the div that you are sliding out. Next time before sliding out check if that value is already set.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94