Changing the size of an image while scrolling

I'm currently working on a website and I'm trying to implement a feature where the logo on the page changes size based on the user's scroll behavior. However, I'm facing difficulty in finding a universal formula that can adjust the logo size effectively across different monitor sizes, as opposed to manually setting coefficients for each monitor.

Below is a snippet of the code I have so far:

$(window).scroll(function() {
            var scroll = window.scrollY
            /*
            var testDiv = document.getElementById("trade"); //this element is the limit to where the picture should be resized (should be same as clients height)
            var move = testDiv.offsetTop-$(window).scrollTop()-66
            console.log(move)
            */
        //all in pixels (px)
        
            var newWidth = 1024 - scroll/1.128 //this number only works for my monitor 
            var newHeight = 223 - scroll/5  //same here
          
            var minWidth = 308; 
            if (newWidth < minWidth) {
                newWidth = minWidth;
            }
            var minHeight = 64;
            if (newHeight < minHeight) {
                newHeight = minHeight;
            }
        
        
            $(".navbar-brand img").css({
                width: newWidth + 'px',
                height: newHeight + 'px'
            });

           
            
        });
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>

<body>
    <div id = "home">
        <nav class = "navbar navbar-expand-lg fixed-top">
            <div class = "container-fluid">
                <a href = "#home" class = "navbar-brand fixed-top" id="navbar-brand">
                    <img id="cover-image" src = "RECMAN-header.png" title = "home">
                </a>
            </div>
        </nav>
        <div class="dataHeight">
        </div>
    </div>
        

    IMAGE SHOULD BE AT ITS SET SIZE (308x64) BEFORE HERE

    <script src="https://code.jquery.com/jquery-3.4.1.min.js">
    </script>
    <script src="script.js"></script>
</body>
</html>
.navbar-brand{
    width: 0;
    padding-top: 2px;
    padding-left: .5%;
}
body{
height:2000px;  
}
.dataHeight{
    height: 100vh;
background-color:lightblue;
}

The goal is for the logo image to decrease in size when scrolling down and increase with scroll up. The resizing should stop once it reaches a certain point before the next element (which equals the window height). I am searching for a precise formula that can adjust the logo size uniformly across various monitor sizes. If you need more details, feel free to ask.

Thank you!

Answer №1

Take a look at the following example:

https://jsfiddle.net/Twisty/1qbth6j8/

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div id="home">
  <nav class="navbar navbar-expand-lg fixed-top">
    <div class="container-fluid">
      <a href="#home" class="navbar-brand fixed-top" id="navbar-brand">
        <img id="cover-image" src="RECMAN-header.png" title="home">
      </a>
    </div>
  </nav>
  <div class="dataHeight">
  </div>
</div>

CSS

.navbar-brand {
  width: 0;
  padding-top: 2px;
  padding-left: 0.5%;
}

.navbar-brand img {
  width: 1024px;
  height: 223px;
  border: 1px solid #222;
}

body {
  height: 2000px;
}

.dataHeight {
  height: 100vh;
  background-color: lightblue;
}

JavaScript

$(function() {
  var ratio = $("body").height() / $(".navbar-brand img").height();
  console.log("Ratio: " + ratio);
  $(window).scroll(function() {
    var scroll = window.scrollY;
    var newWidth = Math.floor(1024 - (scroll * ratio))
    var newHeight = Math.floor(223 - (scroll))

    var minWidth = 308;
    if (newWidth < minWidth) {
      newWidth = minWidth;
    }
    var minHeight = 64;
    if (newHeight < minHeight) {
      newHeight = minHeight;
    }

    console.log("Scroll: ", newWidth, newHeight);
    $(".navbar-brand img").css({
      width: newWidth + 'px',
      height: newHeight + 'px'
    });
  });
});

When users scroll either up or down on the page, the image will adjust its size.

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

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...

Customize the default email validator in AngularJS

I am looking to customize the email validator in AngularJS by using a custom string for validating email addresses. However, when I tried implementing the code provided in the documentation, it doesn't seem to work as expected. Here is the code snippe ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

Arranging fixed-width <div>s in rows of four for a sequential display

Below is the code that I am working with: <div style="margin: 0 auto; display:block; width: 916px; overflow: auto;"> <?php echo ""; echo "<i>Owned: $line->phone </i><br><br>"; $query ...

Is there a way to specifically style my jquery datepicker widget without affecting other elements on the page?

I have customized my main page using a tab-style widget and a specific stylesheet. Recently, I realized the need for a datepicker in my application. To accommodate this, I included the jquery-ui-style.cs stylesheet to my project. The challenge now is that ...

Express.js never terminates a session

I have a Backbone View that makes an Ajax call to the server to delete a session. Upon triggering the following event on the server: app.delete('/session', function(req, res) { if (req.session) { req.session.destroy(function() { ...

Determine whether a specific property value within an array, which is nested within an object, actually exists using Javascript

I am attempting to verify the existence of a property in the given object: var objects = { '1': [ 'A-TheA', 'B-TheB' ], '2': [ 'A-TheA', 'B-TheB' ] } I am seeking to confirm whether &apo ...

What is the best way to obtain the current cursor location in draft.js?

As part of my draftjs project, I'm working on implementing a feature that allows users to easily insert links. One approach I've taken is creating a popup that appears when the shortcut cmk + k is pressed. To enhance the user experience, I am cu ...

Tips for successfully including a positive sign character in string values within JSON in the URL's hash fragment

I am facing an issue with my JS (Angular) app where I load parameters from the URL fragment after the # sign. These parameters contain JSON objects, like this example: ...#filters={"Course":["ST_12.+13.12.2016 [Basel]"]} The aim is to open a data-grid an ...

Adding a simulated $state object to an angular unit test

I'm facing some challenges with Angular unit testing as I am not very proficient in it. Specifically, I am struggling to set up a simple unit test. Here is my Class: class CampaignController { constructor($state) { this.$state = $state; ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

The xhr.upload event listener is triggered when the xhr.responseText is empty after loading

const request = new XMLHttpRequest(); request.open('put', url, false); request.upload.addEventListener('load', function(e) { alert(request.responseText); }, false); Why is the responseText property of the XMLHttpRequest object empt ...

Implementing reCAPTCHA in Spring MVC with Ajax

I've been attempting to implement Google reCAPTCHA service with Spring MVC, but I keep encountering this error in the console: http://localhost:8080/spapp/ajaxtest.htm?name=frfr&surname=frfr&phone=edede…nGi3CCrD9GprYZDn8VHc-pN--SK-u_xoRKOrn ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

VueJS error: 'Property or method is not defined on the instance' message appears despite the method being defined on the instance

Is there a way in Vue.js to dynamically assign the class 'adjust' based on the value of a computed property called "isTrueSet"? I keep encountering the following error message: [Vue warn]: Property or method "itTrueSet" is not defined on the inst ...

Modify the appearance of the username in the header after logging in with Yii

As a fellow coder using Yii, I'm seeking assistance in changing the style of my username displayed in the header upon login. Currently, it's appearing in black color and I desire it to be italicized-white. The code snippet below shows my header s ...

Getting the Kendo UI AutoComplete value onKeyUp within a ViewModel: A step-by-step guide

I'm facing an issue with the Kendo UI AutoComplete. I need to capture the value as the user types in order to send a query to the server for result filtering. The change event only triggers onBlur and not on keyup/down/press events. Additionally, the ...

What causes npm start to fail with a CORS error, but run successfully with HOST=127.0.0.1 npm start?

Currently, I am in the process of creating a basic application that utilizes Flask for the backend and React for the frontend. An issue arises when attempting to initiate my React application through npm start, as it triggers a CORS error. Strangely enough ...

Creating a triangle shape using Bootstrap to style a div element, similar to the image provided

Trying to achieve the look of the attached image with a few divs. I know I can use a background image like this: background:url(image.png) no-repeat left top; But I'm curious if there's another way to achieve this without using a background ima ...