css - Get dynamic background position using jQuery -
i'm trying implement parallax scrolling effect on site (using this tutorial smashing magazine). parallax effect working fine, need 1 of sprites stop scrolling when reaches point. default, continues scrolling until out of view.
the parallax effect works animating background position of element. trying dynamic background position using code:
jquery(function($) { var elem = $("#heart-box"); var backgroundpos = $(elem).css("backgroundposition").split(" "); var xpos = backgroundpos[0], ypos = backgroundpos[1]; $(window).scroll(function() { console.log(ypos); if ( ypos >= 210 ) { $(elem).hide(); } }); });
instead, starting position being returned, defined in css, , isn't changed in console log when page scrolled.
when page scrolled, background y position dynamically changed - range of approximately -200px starting, through 400px @ finish. when background y position reaches 210px, want element have fixed background position of 210px, not keep scrolling.
any great. thanks.
the initial value returned because ypos
set value of backgroundposition outside of scroll
callback. in javascript objects passed reference, backgroundpos
, ypos
, xpos
variables (which primitive types - strings in case) not changed when css property retrieved them changes; have value assigned since never reassign them.
to make work how expecting, need retrieve current background position inside scroll
callback.
$(window).scroll(function() { var backgroundpos = $(elem).css("backgroundposition").split(" "); var xpos = backgroundpos[0], ypos = backgroundpos[1]; console.log(ypos); if ( ypos >= 210 ) { $(elem).hide(); } });
to make more efficient, assign result of $(elem)
variable outside of scroll callback selector not called on every scroll event (more relevant if using string selector):
var elem = $(elem); ... elem.css("backgroundposition").split(" ");
Comments
Post a Comment