Changing styles while scrolling down (javascript)

I am rebuilding my web page, making it more elegant, so I decided that I would change the top panel when the user scrolls down, reduce it and hide some of the elements that it has. I have a function that starts when scrolling down, but for some reason 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 is going wrong because I devote most of my time in php and find a bit of javascript.

I also tried to do this:

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

But also does not work.

My latest javascript code (thanks to Saga 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;
        });
    });
});
+4
source share
2 answers

jQuery , DOM . JS- :

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

, Sagi:

$(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");
    });
});
+3

jQuery.
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");
+3

Source: https://habr.com/ru/post/1607090/


All Articles