Rich-text Reply

Why does this jQuery work in my browser console but not when put into Optimizely?

chrisgosling 09-18-14

Why does this jQuery work in my browser console but not when put into Optimizely?

I'm trying to tun the following code to make a navbar sticky by adding a class to it once it has been scrolled past.  It works when I try it in my browser console but not when I put it into the Optimizely code editor.  Does anyone know why?

 

    var $window = $(window),
       $stickyEl = $('#rdnav'),
       elTop = $stickyEl.offset().top;

$window.scroll(function() {
    $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});

 

Thanks!

Amanda 09-18-14
 

Re: Why does this jQuery work in my browser console but not when put into Optimizely?

Typically when the code works in the console and not in the Optimizely code editor, it's a timing or scoping issue. Can you post the URL of the page you are trying to experiment on so we can take look in more detail?
Optimizely

Re: Why does this jQuery work in my browser console but not when put into Optimizely?

@Amanda is correct - the main issue at hand here is a scoping issue with the variable names you have defined.  Variables defined within Optimizely variation code only have scope within the context of Optimizely.  So when the Optimizely snippet loads, the variables are defined once and the scroll function is bound.  However, as the function is actually subsequently invoked as the user scrolls, Optimizely is not reloading and redefining its variables.  Thus, when the function is being called, its variables are undefined and the code doesn't work.

 

In general, you'll want to append 

window.

to the front of any variable names you define within Optimizely that you wish to be able to access throughout the rest of the page.  However, in your particular case, we can pursue a cleaner approach and avoid extra variable names.  I've updated your variation code to the following:

window.elTop = window.$('#rdnav').offset().top;

window.$(window).scroll(function() {
window.$('#rdnav').toggleClass('sticky', window.$(window).scrollTop() > window.elTop);
});

You'll see that your two of your three initial variable declarations have been eliminated.  This at least gets the nav bar to be sticky.

 

To pursue a finer approach of positioning the stickiness at the top of the page instead of in the middle as it currently stands, I also added

top: 0;

to your Global CSS.

 

Further edits to the positioning of the sticky scroll bar can be pursued within the context of a Support case.  You may email our Support team at support@optimizely.com.

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