KeepoN
KeepoN

Reputation: 137

Change styles when scrolling down (javascript)

I'm rebuilding my webpage, make it more elegant so I decided that I would modify the top bar when the user scrolls down, make it smaller and hide some elements it has. I have the function that triggers when you scroll down, but for some reason it does nothing.

My HTML:

<div class="maindiv">
        <img src="media/cgaline.png" id="cgalinepic" class="cgalinepic"> 
        <a id="right-panel-link" href="#right-panel"><img src="media/menu.png" id="open_menu_button" width="50px" height="50px"></a>
        <h2 class="h1-3" id="h1-3">
            We are not in danger, we ARE the danger.
        </h2>
</div>

I don't know what's going wrong since I dedicate most of my time in php and I find javascript a little hard.

I also tried doing this:

$('#maindiv').style.height = "50px";

But doesn't work neither.

My final javascript code (thanks to Sagi and Ilya Sviridenko):

var div = $('.maindiv');
var pic = $('.cgalinepic');
var menu = $('.open_menu_button');
var text = $('.h1-3');

$(function(){
    var div = $('.maindiv');
    var pic = $('#cgalinepic');
    var menu = $('#open_menu_button');
    var text = $('#h1-3');

    $(document).scroll(function() {
        var lastScrollTop = 0;
        $(window).scroll(function(event){
        var st = $(this).scrollTop();
        if (st > lastScrollTop){
            div.css("height", "50px");
            pic.css({ width : "400px", height : "50px" });
            text.hide();
            menu.css("top", "0px");
        } else {
            div.css("height", "140px");
            pic.css({ width : "800px", height : "100px" });
            text.show();
            menu.css("top", "47px");
        }
        lastScrollTop = st;
        });
    });
});

Upvotes: 4

Views: 430

Answers (2)

Ilya Sviridenko
Ilya Sviridenko

Reputation: 424

You may use jQuery only after DOM is ready. Wrap your JS code like this:

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

Final solution, with Sagi code:

$(function(){
    var div = $('#maindiv');
    var pic = $('#cgalinepic');
    var menu = $('#open_menu_button');
    var text = $('#h1-3');

    $(document).scroll(function() {
        div.css("height", "50px");
        pic.css({ width : "400px", height : "50px" });
        text.css("visibilty", "hidden");
        menu.css("top", "0px");
    });
});

Upvotes: 3

Sagi
Sagi

Reputation: 9284

you are using jQuery already.
Just continue to use jQuery API

div.css("height", "50px");
pic.css({ width : "400px", height : "50px" });
text.css("visibilty", "hidden"); // did you mean to hide the text completly? If so use text.hide();
menu.css("top", "0px");

Upvotes: 3

Related Questions