How to change size of image after scrolling 200px down the screen.

12,006

Solution 1

In pure Javascript:

http://jsfiddle.net/UHAWV/1/

document.addEventListener("scroll", function() {
    scrollHeight = window.pageYOffset;
    document.getElementsByClassName("box")[0].style.height = scrollHeight >= 200 ? "20px" : "";
}, false);

Solution 2

Using jQuery, I would use something like

$( window ).scroll(function() {
     if($(window).scrollTop() > 200){
       $('.box').css({'height': '50'}); 
     }else{
         $('.box').css({'height': '100'}); 
     }

});

HTML

<div class="wrap">
    <div class="header">
        <div class="box"></div>
    </div>
</div>

CSS

.wrap{
    min-height:1000px;
    background:grey;
}

.header{
    position:fixed;
    background:black;
    height:100px;
    width:100%;
    position:relative;
    position:fixed;
    top:0px;
}

.box{
    position:abosolute;
    top:2px;
    left:20px;
    background:red;
    z-index:999;
    height:100px;
    width:100px;
}

jsFiddle demo: http://jsfiddle.net/LLbAu/

Share:
12,006
user2965875
Author by

user2965875

Hi, Designer trying to improve my development skills

Updated on June 04, 2022

Comments

  • user2965875
    user2965875 almost 2 years

    I want to change the size of my div "box" size when you scroll over 200px down the screen.

    I want to make the "box" become 20px in width after the screen has reached 200px or more, The box will also have to return back to its original size once the user has scrolled back up past 200px;

    Do I have to do this in Jquery? If so can any body show me?

    I have made a js fiddle to show my working.

    thanks for your help

    http://jsfiddle.net/UHAWV/

    .wrap{
        min-height:1000px;
        background:grey;
    }
    
    .header{
        position:fixed;
        background:black;
        height:100px;
        width:100%;
        position:relative;
        position:fixed;
        top:0px;
    }
    
    .box{
        position:abosolute;
        top:2px;
        left:20px;
        background:red;
        z-index:999;
        height:100px;
        width:100px;
    }