Scrolling with a Dynamic Twist

Check out this link to see what I'm talking about.

I'm struggling to make the background image behave the way I want it to.

I need the background to automatically resize based on the width of the window, which it currently does correctly. When you adjust the window size, the background adjusts accordingly.

However, here's the problem. If you widen the window, the background resizes and goes too high, disappearing at the top (since the background is positioned at the bottom). I'd like the background to be positioned at the top when you're at the top of the page, and as you scroll down, it gradually moves to be bottom-positioned. Similar to the effect seen on an Android phone's background when you swipe left and right. But remember, I still want the background to resize automatically when the window is made smaller.

html {
  background-color: #70d4e3;
  height: 100%;
}

body {
  height: 100%;
}

.background {
  margin-top: 45px;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: -9999;
}

.banner {
  margin: 0px auto;
  width: 991px;
  margin-bottom: -9px;
}

.content {
  background: url("http://i.imgur.com/daRJl.png") no-repeat scroll center center transparent;
  height: 889px;
  margin: 0 auto;
  width: 869px;
}

.innerContent {
  padding: 30px;
}
<img src="http://i.imgur.com/6d5Cm.jpg" alt="" class="background" />

<div class="banner">
  <img src="http://i.imgur.com/JptsZ.jpg" alt="" />
</div>
<div class="content">
  <div class="innerContent">
    testing
  </div>
</div>

Perhaps some JavaScript or jQuery would be necessary to achieve this effect.

Answer №1

That was an enjoyable project, thank you!

To simplify my workflow and enhance the script's reliability, I have opted to utilize percentages for calculations. This adjustment also ensures that floats with percentages are used consistently.

I have maintained the layout, HTML, and CSS in alignment with the necessary rules for animating the background effectively, keeping them largely unchanged from their original state.

The key was determining the precise calculations required, incorporating the appropriate properties to ascertain your distance from the top. The *20 value represents the percentage of remaining space for the background image (assuming an 80% background height).

I encapsulated these calculations within a function that can be called on scroll events and window resizes, guaranteeing its activation whenever alterations are made to the window dimensions...

While my testing was limited to Chrome, and I admit feeling a bit fatigued, it seems to perform as intended :P

If this aligns with your expectations, please refer to:

http://jsfiddle.net/sg3s/RSqrw/15/ See edit 2

If you desire the opposite effect, with the page background starting at the top, you may adjust accordingly:

http://jsfiddle.net/sg3s/RSqrw/14/ See edit 2

Edit:

In addition, since I had never taken the opportunity to write jQuery scripts as a 'plugin' before, I saw fit to transform this into one. I believe it should prove straightforward to implement and utilize!

http://jsfiddle.net/sg3s/RSqrw/52/

Edit 2:

Upon revisiting the initial question to confirm my approach, I realized it didn't fully align with your requirements. Therefore, I have updated the link provided in the previous edit, offering a plugin that allows for various scrolling background options. It retains my earlier interpretation while accommodating your needs... For additional insights, consult the code comments.

Edit 3:

Reflecting on my work today, I found my previous attempt at creating a plugin to be somewhat bloated. Additionally, as noted in your comment, it did not entirely meet your specifications.

Consequently, I refined the script to focus solely on meeting your specified criteria without any extras, undergoing successful testing in Chrome, Firefox, IE9 + compatibility mode, among others. This revised version is more streamlined and concise.

http://jsfiddle.net/sg3s/vZxHW/

You now have the option to affix the background at either the top or bottom if it fits within the window height. This simplified functionality still offers ample opportunities for creative design endeavors :P

Answer №2

A precise solution: Play around with the code here: http://jsfiddle.net/srGHE/2/show/

Check out the source code

Appreciate the challenge. Below is the solution that meets all requirements, including some optional features with instructions on how to remove them. Only highlighting the modified sections of your page with explanations following each part (CSS, HTML, and JavaScript):


CSS (modifications):

html,body{
    margin: 0;
    height: 100%;
    padding: 0;
}
body{
    background-color: #70d4e3;  
}
#background { /*Previously: .background*/
    /*Removed: margin-top: 45px;
      No other changes*/
}
#banner /*Previously: .banner; no other changes */
#content /*Previously: .content; no other changes */
#innerContent /*Previously: .innerContent; no other changes */

Explanation behind CSS revisions:

  1. The margin-top: 45px in the background is redundant as you're using absolute positioning for the element.
  2. Elements likely to be unique should be targeted via the id (#) selector rather than the class selector for specificity.


HTML (modifications): Replaced all class attributes with ids. No other alterations have been made. Ensure to include the JQuery library as I've utilized JQuery for implementing your requests.


JavaScript (new):
Note: Introduced a feature not requested but rational. The script will automatically adjust left margin space to display the background properly. Remove content between designated comments if this feature is unwanted.

$(document).ready(function(){
    //"Static" variables
    var background = $("#background");
    var marginTop = parseFloat(background.css("margin-top")) || 0;
    var bannerWidth = $("#banner").width(); /*Part of auto left-margin */
    var extraContWidth = (bannerWidth - $("#content").width())/2; /*Same as above*/

    function fixBG(){
        var bodyWidth = $("body").width();
        var body_bg_width_ratio = bodyWidth/1920;
        var bgHeight = body_bg_width_ratio * 926; //Calcs the visible height of BG
        
        var height = $(document).height();
        var docHeight = $(window).height();
        var difHeight = bgHeight - docHeight;
        var scrollDif = $(document).scrollTop() / (height - docHeight) || 0;
        
        /*Start of automatic left-margin*/
        var arrowWidth = body_bg_width_ratio * 115; //Arrow width
        if(bodyWidth - bannerWidth > arrowWidth*2){
            $("body > div").css("margin-left", "auto");
        } else {
            $("body > #banner").css("margin-left", arrowWidth+"px");
            $("body > #content").css("margin-left", (arrowWidth+extraContWidth)+"px");
        }
        /*End of automatic left-margin*/
        
        if(difHeight > 0){
            background.css({top:(-scrollDif*difHeight-marginTop)+"px", bottom:""});
        } else {
            background.css({top:"", bottom:"0"});
        }
    }
    $(window).resize(fixBG);
    $(window).scroll(fixBG);
    fixBG();
});

Explanation of the JavaScript code
The background size is calculated based on the ratio of the background and document width. Width property use ensures accuracy in calculation.

Viewport, document body, and background heights are computed along with potential scrolling offset for background movement optimization when required.

Optionally, the code decides whether adjusting the left margin is necessary to keep the background visible in smaller windows.

If the background arrow surpasses body height, it adjusts position considering scrolling action where the arrow moves up as user scrolls, aligning its bottom to the page end. When no adjustment is needed, the background rests at the page's bottom.

This functionality is attached to Resize and Scroll events upon page load to maintain proper background placement throughout interactions.

For any queries or clarifications, don't hesitate to ask.

Answer №3

It seems like you're looking to add two backgrounds to a webpage, one at the top and one at the bottom. While this may cause issues if the page is too short, there are a couple of ways to achieve this effect. One method involves adding three horizontal divs with different background images and heights, but another option is to use JQuery for better results. Check out for more information on multiple backgrounds in CSS.

Answer №4

After experimenting with jQuery, I managed to create a solution that addresses your specific request:

$(window).scroll(function() {
    var height = Math.max($(document).height(), $(window).height());
    var distanceFromBottom = height - $(".background").height() - $(window).height();
    $(".background").css("top", (($(window).scrollTop() / height) * distanceFromBottom) + "px");
});

UPDATE: I overlooked the need to adjust for the way scrollTop reports position.

Answer №5

Alternatively:

.bg-image {
    margin-top: 30px;
    width: 90%;
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: -999;
    height: 100%;

}

Answer №6

If you're looking to add a background parallax effect to your website, I highly recommend trying out jQuery Background Parallax. You can find more information about it here.

Implementing the function is quite simple:

$("body").backgroundparallax();

Feel free to ask for help if you run into any issues.

Answer №7

Hello @abney! It seems like you are looking for a solution similar to this http://jsfiddle.net/sandeep/RSqrw/60/

You can achieve this effect using only CSS:

#background {    
    position: fixed;
    width: 100%;
    height:100%;
    top: 0;
    left:0;   
    z-index: -1;
}

Answer №8

Looking for a simple solution to your problem? Check out this awesome plugin created by the talented developer, Scott Robin. Visit his project page here to learn more and streamline your projects.

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

Refine the table by selecting rows that contain a specific value in the href attribute of the <a> tag, and display the parent row when the child row

I've been working on filtering and searching the table below based on the href value. My code successfully filters the displayed columns in the table, but it fails to work when I search for a string within the href attribute. For instance, if I searc ...

"Seamlessly connecting Webflow and Nuxt3 for enhanced performance and functionality

Any advice on how to seamlessly integrate a Webflow project into a nuxt one? I've been attempting to transition everything to nuxt, but I'm struggling to incorporate the animations/button functions from webflow (specifically the js file) or fonts ...

Adjust for browser zoom within Three.js CSSRenderer

I'm currently developing a project in three.js using the CSSRenderer and the challenge I'm facing is ensuring that it displays correctly even when the browser zoom is not set at 100%. So far, it appears that: There isn't a way to forcibly ...

Having difficulties rendering photos with django

I am currently in the process of building a blogging platform using the django framework and I have encountered a challenge with displaying images on dynamic pages. Below is the snippet of my code: models.py: class Post(models.Model): title = models.C ...

sending the AJAX request from back to the original JavaScript function

Here presents an issue. I am dealing with an HTML Form that contains a submit button with an onclick=validationFunction(). When this button is clicked, the form values are passed to the mentioned function. Within this function, the form values undergo va ...

Implementing JSON data transfer from PHP to JavaScript in order to create a Google Pie Chart

I've been trying to send JSON data from PHP after running a MySQL query to my JavaScript code that loads the Google Charts API. The query is successful, but it seems like the data format is incorrect. Any suggestions on what I might be doing wrong? I ...

What is the process for loading my new fonts into an HTML document?

I am trying to incorporate two specific fonts, bigsmalls-bold and lft-etica-web, into my CSS and HTML code. Unfortunately, I have been unable to find a way to download these fonts directly. The only information I found was a JavaScript code snippet on I a ...

Ways to eliminate extra space within a text area using angular js

Is there a way to eliminate excess white space at the beginning and middle of a text area when a user enters multiple spaces? The whitespace is counted as characters in this context. Actual Results: https://i.sstatic.net/SPSzP.png Expected Results htt ...

Place the input field and submit button side by side horizontally

How can I align my submit button next to the input text in a single row, with the submit button on the right side of the input text? This is my code: <div class="mt-12"> <input id="grid-text" ...

Retrieve the content of the nearest 'td' element using the '.closest()' method, then locate the desired

I am struggling to assign the value from a <td> to a variable. My approach involves utilizing the closest() and find() methods in jQuery to locate the desired <td>. Interestingly, when I use alert on the <td>, it displays the correct val ...

Creating an opaque effect on a Material UI Drop down menu: Step-by-step guide

For the last half hour, I've been experimenting with my Select dropdown menu in an attempt to make it semi-transparent, but without success. I've tried adjusting the properties of the Paper, then the Menu, and then the MenuList, yet it appears th ...

Memory leaks are occurring due to the texture from the video tag

Currently, I am working on creating a texture in THREE.js (r78) from a video tag and updating the texture 60 times per second by setting needsupdate=true in requestanimationframe. However, I am facing a problem where I notice memory leakage in the Chrome T ...

The three.js object is not displaying its shadow as expected

I am relatively new to Three JS and encountering some difficulties with my code. The main issue I'm facing is the inability to achieve proper shadows for all the objects I've integrated. You can see the problem in the following image: https://i. ...

Error: ReactJS is unable to access the 'focus' property because it is undefined

import React, { Component } from "react"; import PropTypes from "prop-types"; import Textarea from "react-textarea-autosize"; class InputSet extends Component { constructor(props) { super(props); this.state = {}; } static propTypes = { ...

Arrange the array based on the key values

I am currently working with a function that sorts by name and an array containing value/key pairs. I am trying to figure out how I can dynamically pass the key on which the sort is being performed, so that I can call the same function each time with diffe ...

extracting the identifiers and class names from an HTML document

I have successfully extracted tags from an HTML file using getElementByTagName. However, I am also interested in parsing the IDs and class names within the same HTML file. This is my current approach: $html = new DOMDocument(); $html->loadHTML ...

Creating a Form with Dynamic HTML when Button is Clicked

I have been working on enhancing the functionality of my website app located at , but unfortunately, I have not been successful so far. My goal is to introduce a vendor information form with just one click of a button and then enable users to add products ...

Creating a personalized user interface for Material-UI-Pickers with customizable month and day options

Is it possible to modify the number of days in a month? For instance, could I change the default display of Jan-Dec to Month 1-12, with each month having 35 days? I am currently employing the InlineDatePicker component available in Material-pickers v2: & ...

Transform JavaScript variables into CSS variables

Similar Post: Avoiding repeated constants in CSS I am currently working on a javascript file that aims to adjust my site's resolution based on the width and height of the viewport. While I have successfully retrieved these values using JavaScript ...

Struggling to make marker clicks on Google Maps trigger any action

I'm struggling with implementing a simple Google Maps feature. Currently, I have managed to display the map and iterate through a list of projects using PHP (specifically ExpressionEngine). Each project's latitude and longitude are added to a Ja ...