SarmadK
SarmadK

Reputation: 115

How to change width or height of a div whenever page reaches a certain point

I wanted to make a pop out effect with a div. Can someone tell me how to change the width of a div whenever 50% of page is scrolled down. Means that whenever page reaches 50% point, the width of the div should change to 100px, and when it reaches less than 50% or the page is scrolled back to top the div changes back to its orignal width for example 50px. How can I make it using jquery. Here is the basic structure.

http://jsfiddle.net/FpUKU/1/

#box {
    position:fixed; bottom:0; right:0;
    width:50px; height:100px; background:green;
}

Upvotes: 1

Views: 1008

Answers (2)

Malte Bublitz
Malte Bublitz

Reputation: 236

You can get the current scroll position with

$("body").scrollTop()

With

$(document).scroll(function(){
});

You can retrieve the scrollTop whenever the page is scrolled:

$(document.scroll(function(){
   if ($(document).height()/2 < $("body").scrollTop()) {
      $("#box").addClass("wide");
   } else {
      $("#box").removeClass("wide");
   }
}

You should use CSS animations since some Browsers an use 3d hardware acceleration now.

Upvotes: 1

Nikhil N
Nikhil N

Reputation: 4577

Following code will help you..

$(function () {
    $(window).scroll(function () {
        var aheight = $(window).height() / 2;
        if ($(this).scrollTop() >= aheight) {
            $("#box").css("width", "100px");
        }
        else {
            $("#box").css("width", "50px");
        }
    });
});

Check this DemoFiddle

Upvotes: 1

Related Questions