Looking to create an element on a Wordpress site where content starts partway down the screen and then sticks to the top while scrolling. I've tried different approaches without success. My latest attempt involves using Javascript to add and remove a class from the content to achieve this effect.
The script I'm using is:
jQuery( document ).ready(function($) {
alert( "test1!" );
var wrap = $("#wrap");
wrap.on("scroll", function(e) {
if (this.scrollTop > 147) {
wrap.addClass("fix-search");
alert("test2");
} else {
wrap.removeClass("fix-search");
}
});
});
The file is enqueuing correctly as the first test alert ("test1") triggers, but "test2" doesn't fire when scrolling down. This same code worked in a modified version on Codepen (http://codepen.io/anon/pen/NqKKVN), so it seems there might be some issue with Wordpress interacting with Javascript.
If anyone has a solution that works well with WordPress or can help troubleshoot the above code, I'd appreciate it!
EDIT: Issue resolved. For anyone facing similar problems, the code that finally worked for me was:
jQuery( document ).ready(function($) {
var scrollTop = $(window).scrollTop();
function scrollUpdate() {
var scrollTop = $(window).scrollTop();
var wrap = $("#menu-all-pages");
if (scrollTop > 147) {
wrap.addClass("fix-search");
console.log("Menu at top");
} else {
wrap.removeClass("fix-search");
console.log("Menu at set point");
}
console.log(scrollTop);
}
window.onscroll = scrollUpdate;
});