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'
})

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

Combining the inline JavaScript linting tool ESLint with the popular Airbnb configuration and Facebook

In my current project, I am utilizing ESLint and looking to incorporate Facebook flow. However, I am encountering warnings from ESLint regarding flow type annotations. Within the project root directory, I have both .flowconfig and .eslintrc files present. ...

Having trouble with CSS media queries not functioning properly on Internet Explorer version 9?

Incorporated media queries in my design to adjust the width of certain elements on the page according to the browser's width. These are the queries I am using: @media screen and (min-width:1024px) @media screen and (max-width:1024px) Chrome, Safari, ...

CSS animations are failing to work properly in Firefox due to a pseudo-element issue

I'm encountering a problem with my CSS animations in Firefox. Specifically, the animations are not working on a pseudo element (:after) while they work perfectly fine on other browsers. Below is where the animations are being applied: :after { d ...

Using jQuery, set a restriction on the total number of options in three dropdown menus to

I am currently facing a challenge with 3 dropdowns, each containing 8 options. My aim is to restrict the total selection across all three dropdowns to 8. For instance, if I choose 7 in the first dropdown, I should only be able to pick 1 in the next two. Si ...

Python Selenium is having trouble finding the elements

I've been struggling for hours to extract the specific text from a variety of elements on a website. I attached 2 images in hopes that they will help in identifying these elements by their similarities, such as having the same class name. The black un ...

Tips for personalizing Twitter Bootstrap popover concealment animation

Currently, I am interested in creating a unique hide animation for my popover. Instead of directly modifying bootstrap.js, I would like to implement my own custom code. $.fn.popover = function (option) { return this.each(function () { ...

Counting words with JavaScript without using an input tag is a useful skill

Is there a way to count the words in a text using only p and span tags, without using input tags? How can this be achieved? <span class="word" id="word">Words Number</span> <p class="any" id="any"> ...

Materialize.css | managing spaces, indentation, and 'overriding' in a span element

I recently started using a new framework called Materialize CSS for my project and I'm still getting the hang of it. One issue I've encountered is that long texts in my sidebar are creating large spaces between line breaks and strange indents. D ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...

Disable the mousedown event in JavaScript/jQuery

During a drag and drop operation, I have set certain limits on the screen. When the draggable object passes these limits, I want it to return to its original position. The issue I am facing is that if the onmousedown event is active, the object does not r ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

Something seems off with the performance of Gulp-filter and it is not

I am struggling with the following piece of code: gulp.src('src/*.*') .pipe(filter(['**', '!**/*.{png,jpg,bmp,jpeg,jpeg2,webp,svg}', '!**/*.{css,less}'])) .pipe(gulp.dest('dev/')); This code is sup ...

Tips on expanding the dimensions and incorporating more members in a radar graph's Chartjs tag

I need to make some adjustments to the font size and color in a radar chart. Specifically, I want to change the name on the side of each data point. I have already tried adjusting the legend labels using the following code: options={{ ...

What is the best way to implement validation for individual elements within an array that are being displayed on a webpage using a for loop?

Currently, I am utilizing Vue JS within the Vuetify framework to build a dynamic form: <v-text-field v-for="items in itemsArray" :key="items.id" v-model="items.data" :label="items.name" ></v-text-field> ...

Enhanced JQuery Functionality with Additional Parameters

My current class setup is as follows: <div class="photo" parameter1="custom" parameter2="custom"></div> There are a total of 4 parameters in use. I am looking for a solution to pass these parameters within my photo div for JQuery coding, whi ...

Utilizing Node.js and Express to call a function twice - once with the complete req.body and once with an empty body

Trying to articulate this may be a bit challenging, but I'll give it my best shot. I have an iOS app and Android app that both access the same node.js app through their respective web views. The iOS version is able to open the node.js app without any ...

"Learn the steps for accessing the most recent version of a ReactJS application from the server

I have my react app hosted on a Netlify domain. How can I ensure that users who have previously loaded older versions of the app are redirected to the most recent deployed version? ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

Tips for arranging Intervals in sequence?

I've been developing a customized Pomodoro timer with user-defined work and rest times. In my Timer component, I have the following initial logic: useEffect(() => { start(3); start(timeData.workTime); start(timeData.restTime); }, []) c ...

A comprehensive guide on troubleshooting the toggleComplete functionality for React Todo applications

When you click on an item in the to-do list, it should show a strikethrough to indicate completion. However, when I try clicking on an item, nothing happens. Here is my toggleComplete function and where I am attempting to implement it: class ToDoForm exten ...