Updating Background Image Based on Section ID in Lengthy Scrolling Page

Currently, I am customizing a template from HTML5UP (Astral: ). However, I have encountered an issue. My goal is to change the background image with each ID, but every attempt using JavaScript or CSS only modifies the specific section's background instead of the entire page's background. The demo project can be viewed here:

An example of the problem can be seen on this page:

The desired appearance for the section's background should be like this:

To clarify, I want to keep the white background for each section while changing the actual background.

The approach I used that results in the error was:

  <script>
// Changing background image with pure JavaScript 
   document.getElementById('about').style.backgroundImage = 
   'url("assets/css/images/overlay.png"), 
   url("assets/css/images/bg2.png"), 
   url("assets/css/images//bg.jpg")'; 
 </script>
         

In context, the Astral theme is a single long-scrolling page converted to display sections as individual pages. This modification might be causing the section-background problem, which I am struggling to resolve.

I have searched through multiple pages and forums without finding a viable solution. While there are plenty of options for changing backgrounds on usual websites using JS or CSS, none seem to work in my current situation. Thank you in advance for any assistance!

Answer №1

Upon thorough troubleshooting, the most effective method to achieve your desired outcome appears to be as follows.

In main.js, you will find an array named panels[], where each page of your website has its own element. Begin by adding a property in each element that contains the corresponding background-image.

The panels[] array seems to be filled with data from preset frameworks, which are imported on line 89:

panels[id] = t;

If you do not have access to the presets, I recommend creating an object right after line 45, like so:

.on('+desktop', function() {

Inside this block, create the object my_bgs, following the suggestions from my previous response:

var my_bgs = {
    // Adjust the values based on your requirements
    about:'url("assets/css/images/bg1.png")',
    visualize:'url("assets/css/images/bg2.png")',
    approach:'url("assets/css/images/bg3.png")',
    map:'url("assets/css/images/bg4.png")',
    conclusion:'url("assets/css/images/bg5.png")',
    references:'url("assets/css/images/bg6.png")'
}

Subsequently, right after line 89 (panels[id] = t;), include the following code snippet:

panels[id].specialstyle = my_bgs[id];

Then, at lines 178-179, where the code reads:

if (id in panels)
    panels[id]._activate();

Adjust it to:

if (id in panels) {
    panels[id]._activate();
    document.body.style.backgroundImage = panels[id].specialstyle;
}

These modifications should address your issue effectively.

Answer №2

Based on the code provided, it appears that you are successfully changing the background of a specific section (

<article id="about" class="panel">
). If your intention is to change the background of the entire page instead of just the section, you should target document.body rather than document.getElementById('about').

To achieve this, modify your code as follows:

<script>
// Update background image using vanilla JavaScript
document.body.style.backgroundImage = 'url("assets/css/images/overlay.png"), url("assets/css/images/bg2.png"), url("assets/css/images//bg.jpg")'; 
</script>

UPDATE:

Based on new information provided, consider creating a style object for each ID and dynamically setting the background image based on the displayed article.

While this approach may seem cumbersome, it could be necessary if your access to resources is limited.

You can implement this concept as shown below:

<script>
// Update background image using plain JavaScript
var id_styles = {
    about:'url("assets/css/images/bg1.png")',
    visualize:'url("assets/css/images/bg2.png")',
    approach:'url("assets/css/images/bg3.png")',
    map:'url("assets/css/images/bg4.png")',
    conclusion:'url("assets/css/images/bg5.png")',
    references:'url("assets/css/images/bg6.png")'
}
for (var id in id_styles) {
    if (document.getElementById(id).style.display !== 'none') {
        document.body.style.backgroundImage = id_styles[id]; 
    }
}
</script>

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

Suboptimal placement of second submenu in Navbar

This question is inspired by a discussion on Stack Overflow that you can read here. Everything seems to be working fine, except when the 2nd level item is not at the top. In the example provided, the item with the 2nd level menu is the first item. If you m ...

Ways to access data attributes during a Bootstrap 4 popover event

Here is the scenario I am facing. When the popover button is clicked, it triggers the following code: <a href="#" id="popover" data-plan-type="2" data-toggle="popover" data-html="true" data-placement="bottom"> <i class="fal fa-plus-circle">&l ...

I need to modify the ng-style attribute multiple times within a JavaScript function

Here is the structure of my HTML: <nav id="card-set-menu-nav" ng-style="cardSetMenuNavStyle"> ... </nav> In my Javascript code using AngularJS, I have a function called openCardSetMenu: $scope.openCardSetMenu = function(cardSet) { $scope ...

Organize the strings by first sorting them alphabetically based on the first letter and then by length starting from the longest. Next, arrange the strings in ascending

After experimenting and seeking help on stackoverflow, I have managed to sort an array of objects based on the 'plate' key using the following function: sort(function(a, b) { return a.plate.toLowerCase() > b.plate.toLowerCase() ? a.pla ...

What are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

Overlay Image on Card, Overflowing into Card Body

I currently have a webpage featuring cards. Each card includes a thumbnail at the top with an overlay. The main content of the card needs to be positioned outside of the overlay, but it ends up overflowing onto it. Take a look at the demo: https://codepe ...

The Jquery function was implemented twice in the code

I am working on a code snippet that creates progress bars for checkboxes. My goal is to have multiple progress bars on the same page. How can I trigger the function uniquely for each div? $(window).load(function(){ $(function() { $("#reminder").progre ...

a JavaScript method in Selenium for performing a double-click action on a WebElement

Since selenium allows for the execution of JavaScript, I am interested in clicking and double-clicking on a web element or x, y coordinate using JavaScript. I prefer to use JavaScript because the web element in question is a Flash/SVG object on the browser ...

Using Selenium to interact with drop-down lists using div tags instead of select tags

As a newcomer to automated testing using Selenium Web Driver, I am struggling to test drop down lists for the location type without relying on the select command. The element in question is enclosed within a div tag. I attempted sending keys but that meth ...

Using a loop to pass a template to a function and create a dynamic component

I am currently attempting to dynamically generate a component while looping through a list. However, I have encountered an issue where the template cannot be passed to the function for creating the component. The error message indicates that the viewCont ...

A step-by-step guide on splitting an element into two separate elements using jquery

I have the following code snippet: <h4>user (role) on 26 Nov 2018 20:39:42 +00:00:</h4> My goal is to transform it into this structure: <h4>user (role)</h4> <p>on 26 Nov 2018 20:39:42 +00:00:</p> The <h4> eleme ...

Attempting to utilize media queries in order to create a responsive header image

I am currently using Bootstrap 5 to build a website and I am facing an issue with making the header image responsive on mobile devices. While it looks good on desktop, laptop, and tablet screens, on mobile the text and button are not aligning well as they ...

Using multiple html files with ui-router's ui-view feature

Is it possible to create a complex UI using multiple HTML files with ui-view in AngularJS? I am trying to achieve a layout similar to this: I attempted to implement something on Plunker, but it seems like I'm struggling to grasp the underlying concep ...

Unable to perform multi-delete action upon clicking the checkbox button as intended

Within my GridView, I have implemented a Multi-delete feature. Below is the code snippet for your reference:- <script type="text/javascript> function ValidateAll() { var chkselectcount = 0; var gridview = document.getElementById( ...

The NativeAppEventEmitter does not return any value

I've been grappling with obtaining a logged in user access token for quite some time. I initially faced challenges with it in JavaScript, so I switched to Objective-C and managed to succeed. Following that, I referred to this RN guide: https://facebo ...

Tips for Disabling Alert Pop-ups when Launching Desktop Applications from a Browser

Is there a way to prevent the alert pop-up when launching a desktop application from a web browser? For instance, when typing calculator:// in the browser, we want to eliminate the alert box using an Angular TypeScript file. see image reference ...

Triggering the MouseLeave event in Chart.js with Angular

I encountered a situation with my Angular component code and need some guidance. Below is the code in question: Angular component html <canvas myChart> [dataset] = "dataVariable" [labels] = "labelVariable" (chartHover) = "chartHover($event ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

Change the color of the navbar when scrolling using bootstrap and jquery

Using Bootstrap to design a navigation bar, I have two main goals: I want the navbar to change color when the page is scrolled down by 20%, and then revert back to its original color when scrolling back to the top. When the collapse featu ...

Having difficulty accessing and modifying child elements

I am encountering an issue where the 'remove' property is showing as undefined when I try to add or remove a class on an element. Upon inspecting the parent element using element.parentNode, I can see that there are child span elements present. H ...