Increasing the size of a background image as you scroll

Is there a way to adjust the background image of a div so that it scales according to the amount the page is scrolled? The current implementation works fine on desktop screens, but on mobile screens, the height of the background image reduces and the image shrinks. This issue arises when trying to resize a cover image using percentage values. I have also added a red background color to the div for easier debugging. How can this be fixed to work seamlessly even on mobile screens? You can find the code snippet below or visit the full code on Codepen.

HTML:

<main>
  <div class="section_1">
        <div class="welcome_message">            
            <div class="welcome_text">
                <p class="welcome">Welcome to</p>
                <h1>My</h1>
                <p class="tagline">DIRECTORY</p>
            </div>
        </div>
    </div>
</main>

CSS:

main{
min-height: 200vh;  
}

.section_1{
        position: relative;
        width: 100%;
        height: 90vh;
        background: red url(https://images.pexels.com/photos/9467294/pexels-photo-9467294.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260) 40% 10%/cover no-repeat;
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
}

.section_1 .welcome_message{
            width: 80%;
            min-height: 100%;
            display: flex;
            justify-content: flex-end;
            align-items: flex-end;
            background: none;
            padding: 0 1rem 10rem 0;

            .welcome_text{    
                z-index: 3;
                // color: white;
                background-color: rgba(1, 55, 131, 0.5);
                border-bottom: 0.5rem solid white;
                padding: 1rem 2rem;
                border-end-start-radius: 2rem;
            }

            .welcome{
                color: white;
                font-weight: 400;
            }

            h1{
                font-size: 2rem;
                color: white;
                font-weight: 600;
                margin-block: -0.3em;
            }

            .tagline{
                color: white;
                font-weight: 400;
            }
  }

JS:

let bg = document.querySelector('body .section_1')

document.addEventListener('scroll', () => {        
  let x = window.pageYOffset
  bg.style.backgroundSize = (100 + x/10)+'% auto'
})

https://i.sstatic.net/BqRAi.png

Answer №1

you were so close to achieving it by using the calculated width instead of auto, and setting the height to 100%

bg.style.backgroundSize = ''+(130 + x/10)+'% 100%'

Check out the Codepen example here :)

Answer №2

When you scroll to the top once more, the value of bg.style.backgroundSize should be set to null instead of 'auto 130%'.

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

Using HTML to position multiple lines of text alongside an image

I have multiple lines of content and hyperlinks. Additionally, there is an image included. I am looking to have the text aligned on the left with the image on the far right, positioned next to the text. While I attempted to use flexblocks to center everyt ...

Retrieve the output of a Node.js function

I have a function that extracts data from a website and displays it in the console. However, I now want to return this data so I can perform additional actions with it. Instead of using console.log(temperature), I would like to retrieve the temperature v ...

Is it possible to save user inputs in a .json file for future use, and retrieve and reuse them in subsequent sessions or processes?

I am currently developing an account generator using puppeteer and I have a specific requirement for user inputs. The script prompts the user to input necessary variables, but I am interested in exploring the possibility of storing these inputs in a JSON ...

How to Align Paypal Button in the Middle of a Table Cell within a Concealed Form Using HTML and

Currently, I am in the process of developing a payment page that enables payments through Paypal using Instant Payment Notification. The initiation of this process involves sending a POST request to Paypal via a submit button along with multiple hidden for ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

Is there a way to add text to HTML code using CKEditor?

I incorporate CKEditor into my website. When I click on a specific link, it adds some text to the editor successfully. However, when I switch to the source tab, I am unable to append this text to the existing source code. Can anyone offer guidance on h ...

Identifying an Android device using Javascript or jQuery

Is there a way to identify an Android device for styling a mobile website? I want to add specific CSS styles for users on the Android platform. Appreciate any help! ...

Configuring Node.js and express.js for my personal website to showcase my projects

I am new to node.js and I'm excited to implement it on my personal website as a way to start learning. I have successfully set up the node server, but I am struggling with setting up routing using express.js. All my files are typical static files like ...

Tips for displaying a PNG image correctly within the navbar

I'm facing an issue with adding a logo to the navigation bar, as the logo I want to use doesn't display correctly. Even after trying to adjust the width and height, it continues to stretch inappropriately and the text on the image remains unread ...

Challenges when testing Angular controllers using Jasmine - modular problem

Recently, I made the decision to explore testing my Angular code using Jasmine. While everything seems to work fine without specific dependencies, I encountered problems when there are dependencies involved. For instance, in our project we use controllers. ...

In the realm of JavaScript, the localeCompare() string method is more than willing to accept the presence of 'undefined' as a valid parameter for 'locale', while opting to outright reject any instance of

I have discovered a method to sort strings naturally const rows = ['37-SK', '4-ML', '41-NP', '2-YZ', '21', '26-BF']; console.log(rows.sort((a, b) => a.localeCompare(b, undefined, { numeric: tru ...

Creating a feature that uses a button press to initiate an Ajax request based on a specific identifier

I'm looking for the most efficient way to structure a page that involves making Ajax calls. My main issue lies in setting up the event binding for when a user clicks a button. I'm struggling to find a method to pass the ID to the function that t ...

Java servlet, Selenium, and JavaScript are a powerful combination of tools that can

I am facing a situation where I need Selenium webdriver to be executed on the client side. On a webpage, I have a form with a Submit button inside it. The action attribute of the form calls a servlet named "servletName". Inside the servlet, the followin ...

How come the html element doesn't have a default height of 100%?

Is there a reason why the html element is not automatically set at 100% height by default? Can you think of any scenarios where having it take up less than the full height of the window would be beneficial? html { height: 100%; } [Update] I modified th ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

Get the file that is attached for download

Is it possible to download attached files using Paperclip without relying on external libraries? I want to enable users to download the file immediately after uploading, before it reaches the backend. I managed to achieve this using file-saver But I&apo ...

No mouse cursor activity while in Pointer Lock mode

Using Pointer Lock for capturing the cursor in a game being developed in JavaScript with three.js has been quite interesting. Despite extensive online research, the reason why the cursor doesn't seem to move on Chrome OS remains elusive. A working exa ...

What is the best way to adjust inline svg to the user viewport size?

After working on integrating my interactive SVG maps into my HTML pages, I encountered a minor issue: when inserting my inline SVG into a standard, non-responsive HTML document, it automatically adjusts itself to fit nicely within the user's viewport. ...

"Retrieve a list of all routes that have been registered in Node.js

I am trying to retrieve a list of all registered routes in my project. Here is the code I have used for this purpose: const app = require("express"); let routers = app._router.stack .filter((r) => r.route) .map((r) => { return { ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...