Rich-text Reply

Bind event to window

ejr 12-18-14

Bind event to window

I'm trying to A/B test a fixed header for a site, and to test a fixed header I'm trying to toggle a class for the header and compensating for a banner that needs to disappear out of sight. I keep seeing the message "$(...).on is not a function". When removing the 'window' binding, optimizely had no issues with my code. I can only imagine this means that optimizely can't (or won't) bind to the window event, is my assumption correct? And if it is what's the best way of going about this?

 

var offsetTop = $('.top-bar').outerHeight(),
adjustTop = "-9px";

$(window).on('scroll', function() {
if ($(this).scrollTop() > offsetTop) {
$('.header-content').addClass('stickyHeader').css('top', adjustTop).closest('.header').css('z-index', 9001);
} else {
$('.header-content').removeClass('stickyHeader').css('top', '').closest('.header').css('z-index', 1);
}
});

 

ejr
Level 1

JDahlinANF 12-19-14
 

Re: Bind event to window

Try prefacing all of your $ with a "window."

 

var offsetTop = window.$('.top-bar').outerHeight(),
   adjustTop = "-9px";

window.$(window).on('scroll', function() {
   if (window.$(this).scrollTop() > offsetTop) {
      window.$('.header-content').addClass('stickyHeader').css('top', adjustTop).closest('.header').css('z-index', 9001);
   } else {
      window.$('.header-content').removeClass('stickyHeader').css('top', '').closest('.header').css('z-index', 1);
   }
});

 

Re: Bind event to window

Hi @ejr,

 

@nap0leon is correct that placing 

window.

 before your variable names will do the trick.  The short explanation is that variables you declare within Optimizely varition code only have scope within Optimizely.  Once the snippet loads the variables are declared and they are bound to the .on function.  However, as the user scrolls and the function is invoked, Optimizely is not reactivated so the variables do not execute again.

 

A longer explanation with some sample code for a similar situation can be found in this Community post.  Thanks for the great question!

 

Harrison Krat
Solutions Architect | Optimizely, Inc.
harrison@optimizely.com