The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Stop scrolling background image after so long

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #172158

    I have a code I drew up for a site because at the bottom of the page, the background cut off because it wasn’t tall enough.

    jQuery(window).scroll(function() {
    if(jQuery(window).scrollTop() >= 817){
    jQuery(‘html’).attr(‘style’, ‘background-position: 0 -817px !important; background-attachment: fixed !important’);
    jQuery(‘html’).attr(‘style’, ”);

    It works, my question here is, is there a better way I can achieve this? I see it’s comparing the scrolltop and the interger every time the page is scrolled and I know it’s a lot.


    I have 2 solutions for you.

    1. Off the top of my head there IS a janky way you can do it where you make an element (#checker) absolutely positioned in the top left that is 817px tall with a div after it which a container (#container) for the rest of the html, and you apply the background to the container div instead of the html tag. Then in your css you can do something like: #checker:visible ~ #container { background:blah}.

    So if the checker is visible then the container after it will change the background style. This is a pure css solution that doesnt use js and if it works it is probably the best solution performance-wise.

    If you can’t get it to work, let me know and I’ll write up an example.

    1. If you just want to edit your js. You need to add a second check to your IF statement. If scrollTop is greater or equal to 817, you add the background to the htm… BUT what if the html tag ALREADY has the background? Then you’re adding the background to the html tag which already has it.

    So something like if(jQuery(window).scrollTop() >= 817 && jQuery(‘html’).attr(‘style’) == ”)

    This means you only need to add it once and not a million times. Same thing applies to removing the background. Get it to only remove the background once, not a million times.

    This was a quick write up before heading home from work so I hope it makes sense. I’ll check back in tomorrow.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.