I am writing code that makes an svg element appear when it is scrolled to on the page. I only want the code to run once when that position on the page is scrolled to. My plan is to unbind the scroll event (inside the if statement) after that position on the page is scrolled to. For some reason the unbind function is called from within the if statement before that part of the page is scrolled to (400 >= pos). My SVG objects have not been created, which I would expect since the code inside the if statement should not be executed. I suspect the unbind function is bubbling up from the if statement.
function createSVG() {
var pos = $('#graphics').offset().top - $(this).scrollTop();
if(400 >= pos) {
var animation2 = new DrawFillSVG({
elementId: 'obj-1',
drawTime: '2s'
});
var animation2 = new DrawFillSVG({
elementId: 'obj-2',
drawTime: '2s'
});
var animation2 = new DrawFillSVG({
elementId: 'obj-3',
drawTime: '2s'
});
$(this).unbind("scroll");
}
}
$(window).scroll(createSVG());
You need to pass the function refrence of createSVG
to scroll
event.
Use
$(window).scroll(createSVG); //Notice removed ()
As per your current code, You are passing the the return value of createSVG
function to the scroll event.