I am building some code to try and have something happen when an image is within view, then reset the counter when the image isnt in view and have that same thing happen again if the image returns to view.
I have the code working to recognize when the image comes into view and do something, but then when I add the code to reset the counter when the image is out of view the whole thing stops working.
html:
<div style="height: 2000px">
<img height="320px" width= "240px" id="pbr" src="http://i47.tinypic.com/33bztj8.jpg" alt="image 1">
<img height="320px" width= "240px" id="pbrglow" src="http://i48.tinypic.com/2ykduvl.jpg" alt="image 2">
<button id="button">click to reset</button>
</div>
css:
#pbr {
position: absolute;
top: 500px;
z-index: 0;
}
#pbrglow {
position: absolute;
display: none;
top: 500px;
z-index: 1;
}
#button {
position: absolute;
top: 850px;
z-index: 3;
}
javascript:
var y = $("#pbr").offset().top;
var eventsFired = 0;
$(window).scroll(function() {
var y = $("#pbr").offset().top;
var scrollY = $(window).scrollTop();
if (scrollY + 100 > y && eventsFired == 0) {
eventsFired++;
alert(eventsFired);
}
});
$("#button").on("click", function() {
var scrollYY = $(window).offsetTop();
if (eventsFired == 1) {
alert("happened");
eventsFired = 0;
}
}
Here is the jsfiddle with the code
Once I remove the code starting in $(“#button”)… the code works, but with this in the code doesnt.
P.S. this is a website I need to work on iOS.
That’s because your
#buttonclick handler is throwing an error:Uncaught TypeError: Object [object Object] has no method 'offsetTop'You can see it on the jsFiddle page if you have a console open (you can enable the console for mobile Safari via Settings->Safari->Developer).
That problem is that
$(window)doesn’t have anoffsetTop()method. If you get rid of that line (and you don’t need it anyway, since you’re never usingscrollYY), everything works.