Back to Java
2026-02-287 min read

Shrink Header on Scroll (Java)

Learn Shrink Header on Scroll (Java) step by step with clear examples and exercises.

Why This Matters

Shrinking a header on scroll is an essential design practice that enhances user experience by making websites more responsive and visually appealing. By learning how to create a header that shrinks when the page is scrolled down, you will be able to develop engaging and interactive websites that meet modern web standards.

Prerequisites

To follow along with this lesson, you should have a basic understanding of:

  1. HTML (HyperText Markup Language)
  2. CSS (Cascading Style Sheets)
  3. JavaScript (a high-level programming language)
  4. jQuery (a fast and concise JavaScript library)

Before diving into the core concept, it's important to familiarize yourself with these prerequisites if you are not already comfortable working with them. You can find numerous resources online that cover each of these topics in detail.

Core Concept

HTML Structure

First, let's create a simple HTML structure for our webpage:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shrink Header on Scroll</title>
<!-- Include CSS and jQuery -->
<link rel="stylesheet" href="styles.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<!-- Header section -->
<header id="header">
<h1>Shrink Header on Scroll Example</h1>
</header>

<!-- Main content section -->
<main>
<h2>Main Content</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus lacinia odio vitae vestibulum interdum.</p>
<!-- Add more content as needed -->
</main>

<!-- Footer section -->
<footer id="footer">
<p>&copy; 2023 Shrink Header on Scroll Example</p>
</footer>
</body>
</html>

CSS Styles

Next, we'll create a separate CSS file (styles.css) to style our webpage:

/* Reset default browser styles */
* {
margin: 0;
padding: 0;
}

/* Set up basic layout */
body {
font-family: Arial, sans-serif;
}

header#header {
background-color: #333;
color: white;
height: 100px; /* Initial header height */
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}

main {
padding: 20px;
}

footer {
background-color: #333;
color: white;
text-align: center;
padding: 10px;
}

JavaScript and jQuery

Now, we'll write the JavaScript code that will make our header shrink when the page is scrolled down. We'll use jQuery to simplify the process:

$(document).ready(function() {
// Initialize variables
var windowHeight = $(window).height();
var headerHeight = $('#header').outerHeight();
var scrollPosition = 0;

// Function to update scroll position and adjust the header's height
function updateScroll() {
scrollPosition = $(this).scrollTop();

if (scrollPosition > windowHeight - headerHeight) {
$('#header').css('height', '60px'); /* Set new, smaller header height */
} else {
$('#header').css('height', '100px'); /* Reset initial header height */
}
}

// Attach the scroll event listener to the window object
$(window).scroll(updateScroll);

// Call updateScroll function once on page load to set initial header height
updateScroll();
});

Worked Example

Save the HTML, CSS, and JavaScript code above in separate files (index.html, styles.css, and script.js) in a folder named "shrink-header-scroll." Open the index.html file in your web browser to see the working example.

In this worked example, we have created a simple HTML structure, applied some basic CSS styles, and used jQuery to make the header shrink when the page is scrolled down. You can modify this example to suit your specific needs or create more complex designs by adding additional content and features.

Common Mistakes

  1. Forgetting to include jQuery: Make sure you link to the jQuery library (``) in your HTML file's head section.
  2. Incorrect selector for header: Use $('#header') instead of simply $('header') to target the specific header element with an ID attribute.
  3. Syntax errors in JavaScript/jQuery code: Double-check that your script.js file contains valid JavaScript and jQuery syntax, with no missing semicolons or brackets.
  4. Not attaching the scroll event listener: Make sure you call $(window).scroll(updateScroll); to attach the scroll event listener to the window object.
  5. Incorrect calculation of scroll position: Ensure that your JavaScript code calculates the correct scroll position using $(this).scrollTop();.
  6. Not updating the header's height correctly: Make sure that you set the new, smaller header height when the scroll position exceeds the calculated height difference between the window and the header.
  7. Not resetting the initial header height on page load: Call updateScroll() function once on page load to set the initial header height.

Practice Questions

  1. Modify the example to make the header grow when the user scrolls up.
  2. Add a class named "shrunk" to the header element when it shrinks, and remove it when it returns to its initial height. Use CSS transitions to animate the change in height.
  3. Implement a function that toggles the visibility of a navigation menu when the user clicks on the header.
  4. Add a responsive design so that the header shrinks at different breakpoints based on screen size.
  5. Create a custom animation for the header's transition between its initial and smaller heights using CSS keyframes.
  6. Modify the example to make the header shrink more gradually as the user scrolls down, rather than suddenly changing height.
  7. Implement a function that adjusts the header's height based on the content within it, ensuring that the header never exceeds a maximum height.
  8. Add a sticky navigation bar that remains fixed at the top of the screen when the user scrolls down.
  9. Create a dynamic header that changes its background color based on the current page or section the user is viewing.
  10. Implement a smooth scrolling feature that scrolls to a specific section of the page when the user clicks on a link within the header.

FAQ

  1. Why is my header not shrinking? Check if you have included jQuery and attached the scroll event listener correctly. Also, ensure that your JavaScript code does not contain any syntax errors.
  2. Can I use vanilla JavaScript instead of jQuery for this task? Yes, it's possible to achieve the same result using pure JavaScript, but jQuery simplifies the process by providing a more concise API and cross-browser compatibility.
  3. How can I make the header grow back when the user scrolls up? You can use the $(window).scroll() function with a condition that checks if the scroll position is less than the calculated height difference between the window and the header. If the condition is true, you can set the header's height back to its initial value.
  4. Why does my header not animate when shrinking or growing? To add animations, you can use CSS transitions on the height property of the header element. Make sure that you have defined the necessary transition properties in your CSS file (e.g., transition: height 0.5s ease;).
  5. Can I make the header shrink at different breakpoints based on screen size? Yes, you can create media queries in your CSS to apply different styles depending on the screen size. For example, you could define a new style for small screens (e.g., @media only screen and (max-width: 600px)) that sets a smaller initial height for the header.
  6. How can I make the header shrink more gradually as the user scrolls down? You can adjust the threshold at which the header starts shrinking by changing the value of windowHeight - headerHeight in the JavaScript code. A lower value will result in a more gradual shrink effect.
  7. Why is my header not sticking to the top when I scroll down? Make sure that you have defined the correct CSS properties for the sticky header, such as position: fixed; and setting the top property to 0. You may also need to adjust the z-index of the sticky header to ensure it appears above other elements on the page.
  8. How can I change the background color of the header based on the current page or section? To achieve this, you can use JavaScript to detect the active element (e.g., a specific div or section) and apply the corresponding CSS class to the header. This class can define the desired background color for that particular page or section.
  9. How can I implement smooth scrolling when clicking on links within the header? You can use jQuery's animate() function in combination with the scrollTop() method to create a smooth scrolling effect. Make sure to add an event listener to each link that triggers the smooth scrolling function and passes the target element as a parameter.
  10. How can I create a custom animation for the header's transition between its initial and smaller heights? To create a custom animation, you can use CSS keyframes and define the desired animation properties in your CSS file (e.g., @keyframes shrink { ... }). Then, apply this animation to the header element using JavaScript or jQuery when the scroll position exceeds the calculated height difference between the window and the header.
Shrink Header on Scroll (Java) | Java | XQA Learn