Rich-text Reply

Sticky Ad on scroll not working

dvdschwrtz 06-17-16

Sticky Ad on scroll not working

Ok, so I have an ad that is on the bottom of the right sidebar.  The problem occurs when I try to have the ad remain in view when scrolling down the page. I looked through the help forums and added "window." to my code so that Optimizely registers the variables. I am getting the error "window.$ is not a function" for the window.adTop line. What is going on here. I have tried several things to get this working in optimizely. Thanks!

 

// move the ad to the bottom of the sidebar. It is not there on the original version.

$("#google_ads_iframe_\\/4879\\/Pets\\.n_TN\\/cats_3").css({"left":"0px", "position":"relative", "top":"0px"});
$("#google_ads_iframe_\\/4879\\/Pets\\.n_TN\\/cats_3").detach().insertAfter(".col-md-3 > div:eq(3)");

 

// here is where I can't get it to keep the ad visible when scrolling

window.adTop = window.$("#google_ads_iframe_\\/4879\\/Pets\\.n_TN\\/cats_3").offset().top;

window.$(window).scroll(function() {
  window.$("#google_ads_iframe_\\/4879\\/Pets\\.n_TN\\/cats_3").toggleClass('sticky', window.$(window).scrollTop() > window.adTop);
});

dvdschwrtz 06-17-16
 

Re: Sticky Ad on scroll not working

CouchPsycho 06-17-16
 

Re: Sticky Ad on scroll not working

Just an idea: remove the window when calling jQuery/$...

And: Where do you use this code: experiment-js or variation-js?



"the essence of the creative act is to see the familiar as strange." (anonymous)
dvdschwrtz 06-17-16
 

Re: Sticky Ad on scroll not working

I tried removing the 'window.' when calling jQuery and left the window.adTop, but it still did not work. Thanks for the help though. I ran this in the <edit code> section at the bottom of one of my variations
dvdschwrtz 06-17-16
 

Re: Sticky Ad on scroll not working

My whole account is acting buggy now. It is saying that $(...).on is not a function when I am just trying to implement some basic click tracking...

$(".mobile-leaderboard").on("mousedown", function() { window.optimizely.push(['trackEvent', 'mobile-leaderboard']); });

Re: Sticky Ad on scroll not working

Hi @dvdschwrtz,

 

Thanks for reaching out to me about this jQuery issue.  I'll share my thoughts here in hopes that they'll benefit other members of the community.

 

I think your issues may be related to scope - that is, the Optimizely editor doesn't have access to jQuery functions you're trying to use in your code unless you tell us where and how to access those functions.

  • Within the Optimizely editor, you only have access to the version of jQuery your snippet includes, which currently is a trimmed version of 1.6.4.
  • This trimmed version of 1.6.4 does not include the $.offset(), on(), and scrollTop() methods, among others (see attached jquery_1.6.4_included.txt file).  If you want to use these methods, or other methods you have on your site, within the editor, normally we would recommend what you have done - amend all your selectors to use window.optimizely or window.$ to widen their scope and give them access to your jQuery (which is now available because your page has fully loaded in the editor).
  • However, while on your page you're loading 1.11.3 and thus we would expect the window. appendage to work, the issue is that you're loading your jQuery above the Optimizely snippet.  When we clean up the dollar sign, jQuery no longer belongs to the global scope.  You can verify this on your page, outside of Optimizely, by opening the browser console and typing window.$.fn.jquery - you'll see an error returned that jQuery is undefined.
  • The recommended solution is to have a Project Owner or Administrator change your Optimizely snippet to use the full version of 1.11.3, and then you should be able to access these methods as soon as Optimizely loads.  Using window.optimizely or window.$ won't be necessary.
  • If you then need further assistance with the actual variation code itself, you can start with the modified code I suggested further down in the other thread you linked.  If I recall, Chris also had the 'sticky' class defined in Experiment CSS.
  • You can read more about our jQuery settings in this Knowledge Base article.  We're in the process of updating the function listings.

Please let me know if this helps.

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

Re: Sticky Ad on scroll not working

I was unable to attach the jQuery text file, so here it is:

 

Included in trimmed version of 1.6.4:
"$._data", "$._Deferred", "$._mark", "$._unmark", "$.acceptData", "$.access", "$.attr", "$.attrFix", "$.attrFn", "$.attrHooks", "$.bindReady", "$.boxModel", "$.browser", "$.buildFragment", "$.cache", "$.callBaseMethod", "$.camelCase", "$.clean", "$.cleanData", "$.clone", "$.contains", "$.css", "$.cssHooks", "$.cssNumber", "$.cssProps", "$.curCSS", "$.data", "$.Deferred", "$.dequeue", "$.dir", "$.each", "$.error", "$.event", "$.Event", "$.expando", "$.expr", "$.extend", "$.filter", "$.find", "$.fn", "$.fragments", "$.getBaseMethod", "$.getBaseType", "$.getInterfaces", "$.getName", "$.globalEval", "$.grep", "$.guid", "$.hasData", "$.holdReady", "$.implementsInterface", "$.inArray", "$.inheritsFrom", "$.initializeBase", "$.isArray", "$.isEmptyObject", "$.isFunction", "$.isImplementedBy", "$.isInstanceOfType", "$.isNaN", "$.isPlainObject", "$.isReady", "$.isWindow", "$.isXMLDoc", "$.makeArray", "$.map", "$.merge", "$.noConflict", "$.noData", "$.nodeName", "$.noop", "$.now", "$.nth", "$.parseJSON", "$.parseXML", "$.prop", "$.propFix", "$.propHooks", "$.proxy", "$.queue", "$.ready", "$.readyWait", "$.registerClass", "$.registerEnum", "$.registerInterface", "$.removeAttr", "$.removeData", "$.removeEvent", "$.resolveInheritance", "$.sibling", "$.style", "$.sub", "$.support", "$.swap", "$.text", "$.trim", "$.type", "$.uaMatch", "$.unique", "$.uuid", "$.valHooks", "$.when", "$a", "add", "addClass", "after", "andSelf", "append", "appendTo", "attr", "before", "bind", "blur", "change", "children", "clearQueue", "click", "clone", "closest", "constructor", "contents", "css", "data", "dblclick", "delay", "delegate", "dequeue", "detach", "die", "domManip", "each", "empty", "end", "eq", "error", "extend", "filter", "find", "first", "focus", "focusin", "focusout", "get", "has", "hasClass", "hover", "html", "index", "init", "insertAfter", "insertBefore", "is", "jquery", "keydown", "keypress", "keyup", "last", "length", "live", "load", "map", "mousedown", "mouseenter", "mouseleave", "mousemove", "mouseout", "mouseover", "mouseup", "next", "nextAll", "nextUntil", "not", "one", "parent", "parents", "parentsUntil", "prepend", "prependTo", "prev", "prevAll", "prevUntil", "promise", "prop", "push", "pushStack", "queue", "ready", "remove", "removeAttr", "removeClass", "removeData", "removeProp", "replaceAll", "replaceWith", "resize", "scroll", "select", "selector", "siblings", "size", "slice", "sort", "splice", "submit", "text", "toArray", "toggle", "toggleClass", "trigger", "triggerHandler", "unbind", "undelegate", "unload", "unwrap", "val", "wrap", "wrapAll", "wrapInner"

 

Included in full version of 1.6.4:
All of the above, and:
"_toggle", "$.active", "$.ajax", "$.ajaxPrefilter", "$.ajaxSettings", "$.ajaxSetup", "$.ajaxTransport", "$.easing", "$.etag", "$.fx", "$.get", "$.getJSON", "$.getScript", "$.lastModified", "$.offset", "$.param", "$.post", "$.speed", "$.timers", "ajaxComplete", "ajaxError", "ajaxSend", "ajaxStart", "ajaxStop", "ajaxSuccess", "animate", "fadeIn", "fadeOut", "fadeTo", "fadeToggle", "height", "hide", "innerHeight", "innerWidth", "offsetParent", "outerHeight", "outerWidth", "position", "scrollLeft", "scrollTop", "serialize", "serializeArray", "show", "slideDown", "slideToggle", "slideUp", "stop", "width"

Harrison Krat
Solutions Architect | Optimizely, Inc.
harrison@optimizely.com
 
robertchan 06-21-16
 

Re: Sticky Ad on scroll not working

Assuming you are using the trimmed version of jQuery, but want to use scrollTop and more, you can append the latest version of jQuery to the head of your document with the following:

 

var js = document.createElement("script"),
					    	he = document.getElementsByTagName('head')[0];
						    js.type = "text/javascript";
						    js.src="http://code.jquery.com/jquery-3.0.0.min.js";
						    he.appendChild(js);
						    js.addEventListener("load", function () {
						        console.log('jQuery is now a ' + typeof $);
						    });
						console.log('jQuery was not present, but has now been added');

Once this has been added, you can test your code again, placing it in a callback after the previous code has run. If your code is still not working, you can play around with scoping things out to window. Below, is an example of code I created that was inserted into Experiment JavaScript&colon;

 

$('body').append('<div id="optslidebox"></div>');
$(".slide-content > p").attr("id", "last");

window.scrollBox = function() {
	$(window).scroll(function(){
		/* when reaching the element with id "last" we want to show the slidebox. Let's get the distance from the top to the element */
		var distanceTop = window.$('#last').offset().top - window.$(window).height();

		if(window.$(window).scrollTop() > distanceTop){
			window.$('#optslidebox').animate({'right':'0px'},300);
		} else { 
			window.$('#optslidebox').stop(true).animate({'right':'-430px'},100);   
		}
	});

	/* remove the slidebox when clicking the cross */
  
};

Next, in the variation code, I did the following:

 

window.scrollBox();
window.variationHtml = [
  '<a class="close"></a>',
  '<p>Title of Your Slidebox</p>',
  '<h2><a href="http://google.com">Some Link for Users to Check Out</a></h2>',
].join('');
/* _optimizely_evaluation=safe */
$("#optslidebox").html(variationHtml);
  
window.$('#optslidebox .close').on('click', function(){
	$(this).parent().remove();
});

Hopefully that should work for you. If you're not comfortable with setting jQuery on the fly, you can also change whether you're using the trimmed version of jQuery in your settings. Just note that you're snippet size will increase or decrease depending on whether you're using trimmed or not trimmed versions of jQuery.

Robert Chan

Experimentation Hero