Optimizing Div Heights with jQuery Scroll

As I scroll down, I want the height of a specific div to decrease instead of the window itself scrolling. The code snippet below illustrates the simple div header setup that I am using:

<html>
    <head>
        <title>Test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="javascripts/headani.js"></script>
    </head>
    <body>
        <div id="pageTop"></div>
        <div id="pageArticle">
            <div class="siteDesc">
                <p id="hello"></p>
            </div>
        </div>
    </body>
</html>

The corresponding CSS for this is as follows:

body {
    margin: 0 0 0 0;
    background-color: beige;
}
#pageTop {
    width: 100%;
    height: 450px;
    background-color: tan;
}
#pageArticle {
    width: 100%;
    height: 1000px;
    background-color: rgba(0,0,0,0);
}
#siteDesc {
    height: 500px;
    background-color: black;
    width: 1000px;
    margin: auto;
}

Additionally, here is the jQuery implementation (please note that it's a rough model with testing variables):

$(document).ready( function() {
    var headHeight = $('#pageTop').height();
    $(window).scroll(function() {
        if (headHeight > 50) {
            $(document).bind("scroll", function(e) {
                e.preventDefault;
            })
            headHeight = (headHeight - 1);
            $('#pageTop').css('height', headHeight);
        }
        $('#hello').html($(document).scrollTop() + "<br/>" + headHeight);
    })
});

I have successfully managed to minimize the div on both scroll up and scroll down actions, but my issue lies in preventing the body from scrolling until the height of 'pageTop' is reduced to 50. I attempted to bind the scroll event but encountered some challenges! Any suggestions on how best to accomplish this?

Answer №1

It seems that the scroll event is triggered immediately after the scrolling has occurred, making it impossible to prevent the default action because it has already happened. One workaround is to listen for the wheel event and the keydown event to intercept the action.

$.fn.scrollEvent = function(handler) {
  this.on('wheel', function(e) {
    handler(e);
  });
  this.on('keydown', function(e) {
    if (e.which === 40) {
      handler(e);
    }
  });
};

$(document).ready(function() {
  var headHeight = $('#pageTop').height();
  window.scrollEvent
  $(window).scrollEvent(function(e) {
    if (headHeight > 50) {
      e.preventDefault();
      e.stopPropagation();
      headHeight = (headHeight - 30);
      $('#pageTop').css('height', headHeight);
    }
    $('#hello').html($(document).scrollTop() + "<br/>" + headHeight);
    return false;
  });
});
body {
  margin: 0 0 0 0;
  background-color: beige;
}
#pageTop {
  width: 100%;
  height: 450px;
  background-color: tan;
}
#pageArticle {
  width: 100%;
  height: 1000px;
  background-color: rgba(0, 0, 0, 0);
}
#siteDesc {
  height: 500px;
  background-color: black;
  width: 1000px;
  margin: auto;
}
<html>

<head>
  <title>Test</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  <script src="javascripts/headani.js"></script>
</head>

<body>
  <div id="pageTop"></div>
  <div id="pageArticle">
    <div class="siteDesc">
      <p id="hello"></p>
    </div>
  </div>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending information to a server using JavaScript

Greetings everyone, this is my first time posting here and I would appreciate detailed guidance in your comments. Just a little background about myself: I am a second-year college student with one year of Python training. I only recently started learning ...

Obtain cell information when clicking on a specific field within a material-table

import MaterialTable from "material-table"; import ShipmentContext from "../context/ShipmentContext"; const ItemsTable: React.FC = () => { const shipmentcontext = useContext(ShipmentContext); const { filtered } = shipmentcontex ...

What is the best way to add pairs of divs to a single div?

Can you help me with this task? <div id="list"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div& ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

What is preventing the successful insertion of a JSON array into a SQL database?

I am facing an issue with inserting a JSON array into an SQL database. I have an HTML table that stores its data in a JavaScript array, converts it to a JSON array, and then sends it to a PHP file. However, when trying to insert this JSON array into the da ...

Converting a intricate hexadecimal code into an emoji is not possible

Is there a way to convert a hex code into an emoji without using surrogate pairs? For example, I want to turn the hex code U+1F64C into its corresponding emoji, without complications like using simple hex values like 2728 or more complex ones like 1F601. ...

Troubleshooting Problem with ListItem Alignment in Material UI v0 involving Custom Avatar Component

Material UI version: v0.20.0 I'm facing an issue with aligning the leftAvatar value using the CustomAvatar component, as shown in the attached screenshot. Any assistance would be appreciated. CustomAvatar: The functionality of this component is cond ...

Is it possible to use CSS to create a fading effect on the edges of a div

I am looking to implement a mobile modal popup that will show a success message. Currently, I am working to add a semi-transparent overlay to the entire screen using this CSS: .overlay { position:fixed; top:0px; left:0px; width:100%; h ...

Iterating through an array in Javascript to create a new array filled with objects

Is there a way to iterate through an array of strings and convert them into an array of objects based on their values? For instance, if the array looks like this: [a,a,a,b,b,c,d] I aim to cycle through the array and create objects with key-value pairs t ...

Can Mongoose be integrated into a Next.js API environment?

My current project involves creating a website for my sister to showcase and sell her artwork. Utilizing Next.js, I have set up the framework where the website displays the artwork by fetching an array from a database and iterating through it. Let's ...

Sending the ID from jQuery to PHP

Coding Example <a href="#modal" id="a1" class="leftPanel">Link1</a> <a href="#modal" id="a3" class="leftPanel">Link1</a> <a href="#modal" id="a4" class="leftPanel">Link1</a> jQuery Logic function processLinks() { ...

Having trouble removing the uploaded image from the system

HTML/GSP <li class="gallery-item"> <form> ..... <a data-portfolio-id="${portfolioInstance?.id}" data-id="${part.id}" class="btn-delete" href="javascript:void(0);"> </form> </li> JS $('.btn-delete').click(func ...

How can I create a drop-down list in Bootstrap 4 input?

Displayed below is an example of a customized button dropdown featuring material icons and the Google Roboto Mono font, ideal for optimal spacing. My inquiry pertains to replicating this behavior with an input field. <!-- Bootstrap CSS --> < ...

Retrieve the href attribute using jQuery when clicked

Is there a way to capture the href link using jQuery? For instance, consider the following: <li><a href="head.php">Head</a></li> <li><a href="body.php">Body</a></li> <li><a href="settings.php">S ...

Struggling with modifying css attribute in a JQuery Chrome Extension

I have a basic chrome extension that I utilize on a specific URL to make slight adjustments to the page layout (such as color and position). Now, I am attempting to apply the same modifications to a new URL. The code I am using for both URLs is identical, ...

Guide on excluding a specific element using an Xpath expression

I am seeking a solution to craft an XPath expression that can target all <p> elements except for p[6] and p[7]. Currently, I have formulated this expression: //div[@class="Job-Description app-responsive-jd"]/p[1], which is functioning corre ...

Animate a dotted border with CSS

How can I make a text block with a dotted style border move like a gif image using CSS at runtime? ...

How can I create a DIV element that consistently shows text when clicked?

Is there a way to achieve this effect using just CSS and HTML? When clicking on the question text, it should reveal the answer below, and clicking again should hide the answer. I have managed to make it work with hover, but I am unsure how to implement it ...

The unusual spinning behavior of child elements in three.js

My current project involves implementing an experimental version of a 2x2x2 Rubik's Cube. I have gathered insights from two previous posts that addressed issues related to attaching and detaching child objects in Three.js: Three.js: Proper way to add ...

Tips on updating the initial value of a select box or placeholder?

Here is a select input: <select name="" id=""> <option disabled hidden selected value=""> default </option> <option value="2">2</option> <option value="3">3</option> <option value="3">3</option> ...