DarkReaperRising DarkReaperRising - 4 years ago 166
Javascript Question

Header Change on Scroll

On a site I am creating in which I want to put a header that changes size on scroll. I have done 2 methods which should in theory have worked. This header is part of a larger document which contains JS and when I tested the other JS was working so I don't believe is a major syntax error. Also when I inspect elemented it I didn't see any errors in the console.



$(document).on('scroll', function(e) {
var value = $(this).scrollTop();
if ( value < 100 )
$("header").css("height", "100px");
else
$("header").css("height", "45px");
});

header {
height: 300px;
background-color: #69D2E7;
font-family: 'Raleway', sans-serif;
z-index: 30;
width: 100vw;
box-shadow: 1px 1px 10px rgba(40, 40, 40, 0.6);
position: fixed;
}

<header>
<a href="index.html">
<h1>MEH Web Design</h1>
</a>
</header>




Another method I attempted to do that also did not work was:



$(function() {
var header = $(".hlarge");
$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll >= 200) {
header.removeClass('hlarge').addClass("hsmall");
} else {
header.removeClass("hsmall").addClass('hlarge');
}
});
});

.hlarge {
height: 300px;
background-color: #69D2E7;
font-family: 'Raleway', sans-serif;
z-index: 30;
width: 100vw;
box-shadow: 1px 1px 10px rgba(40, 40, 40, 0.6);
position: fixed;
}
.hsmall {
height: 150px;
background-color: #69D2E7;
font-family: 'Raleway', sans-serif;
z-index: 30;
width: 100vw;
box-shadow: 1px 1px 10px rgba(40, 40, 40, 0.6);
position: fixed;
}


<header class="hlarge">
<a href="index.html">
<h1>MEH Web Design</h1>
</a>
</header>




During the second one the JS wouldn't even change the class

Answer Source

I don't think in either of your examples was the body tall enough for scrolling to happen.

$(document).on('scroll', function(e) {
    var value = $(this).scrollTop();
    if ( value < 100 )
        $("header").css("height", "100px");
    else
        $("header").css("height", "45px");
});
header {
    height: 300px;
    background-color: #69D2E7;
    font-family: 'Raleway', sans-serif;
    z-index: 30;
    width: 100vw;
    box-shadow: 1px 1px 10px rgba(40, 40, 40, 0.6);
    position: fixed;
}

body {
  min-height:1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header>
    <a href="index.html">
      <h1>MEH Web Design</h1>
    </a>
  </header>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download