Reputation: 859
I need help with this since it's showing and I tried with global variable etc an issue remains..
var $ = jQuery;
var $window = $(window),
$moving1 = $(".scroller1"),
$holder1 = $("#scroller-wrap1"),
offset1;
$window.load(function() {
offset1 = $holder1.offset();
});
$window.scroll(function() {
if ($window.scrollTop() > offset1.top) {
$moving1.addClass('fixed');
} else {
$moving1.removeClass('fixed');
}
if ($window.scrollTop() > (offset1.top + $holder1.height() - $moving1.height() - 60)) {
$moving1.removeClass('fixed', 1000);
}
//console.log("scroll: " +$window.scrollTop());
});
Basically I am checking if the windows if fully loaded so I can make the calculations without error but I guess it's not correct.
This is inside wordpress that's why I need the jQuery part.
Upvotes: 0
Views: 40
Reputation: 65796
Ok. The error is coming from this command:
if ($window.scrollTop() > offset1.top) {
and it means that offset1
is undefined
. Now, you are initializing offset1
in your .load
event, but you are setting it equal to $holder
and $holder1
is initialized before the document is ready, so it becomes undefinded
.
Your code can be reduced greatly by just adding a document.ready
function. You also don't have to do this var $ = JQuery
as that is automatic.:
// Passing a function to JQuery creates a "document.ready()" callback
// function that will automatically be executed when the DOM is built.
$(function(){
var $window = $(window);
var $moving1 = $(".scroller1");
var $holder1 = $("#scroller-wrap1");
var offset1 = $holder1.offset();
// JQuery recommends the use of the .on() function to bind
// event callbacks as opposed to event methods.
$window.on("scroll", function() {
if ($window.scrollTop() > offset1.top) {
$moving1.addClass('fixed');
} else {
$moving1.removeClass('fixed');
}
if ($window.scrollTop() > (offset1.top + $holder1.height() - $moving1.height() - 60)) {
$moving1.removeClass('fixed', 1000);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2