Alter the background image of the body based on the active ID and class

Currently, I am developing a website where all the pages slide around on the main landing page. The process starts with a div having an ID of "main" and a class of "currentpage." When navigating through the menu items, the content slides away to reveal the next page's content. Each new page has its own unique ID (for example, #about) along with the "currentpage" class added to it.

One issue I encountered is related to the body tag, which has a background image attached to it. Initially, each page had its own background image specified, but due to padding in the primary div, the original image from the body tag still showed behind the specified background image for that particular page. As a solution, I want to dynamically change the body tag's background image based on the currently active page ID.

I believe step one would involve checking whether a specific ID is being displayed and if the corresponding div has the "currentpage" class. Step two would then entail changing the background image accordingly.

Here are the attempts I made, none of which worked successfully:

Attempt 1:

if ($this.is('#about')) { 
$('.bgimage').css({"background":"url(imageurlhere)"});

}

The above code did not produce any results as expected.

For my second attempt, I modified an old thread from Stack Overflow to test whether the concept was heading in the right direction. Here is the altered code snippet:

Attempt 2:

if ($("#about").hasClass("currentpage")) {
$('#about').css({"background-color":"red"});

}

Unfortunately, this also did not yield the desired outcome when navigating to the About page.

I ensured to clear the cache after each attempt and verified the presence of updated code blocks in the JS file manually.

Edit
The basic layout of the page includes the following structure:

<body class="video">
<div class="preload">Content for preload overlay</div>
<nav>Site navigation here</nav>
<main>
    <div id="pt-main" class="pt-perspective ">
        <div class="page-1 currentpage" id="main"></div>
        <div class="page-2" id="about"></div>
        <div class="page-3" id="services"></div>
        <div class="page-4" id="portfolio"></div>
        <div class="page-5" id="contact"></div>
    </div>
</main>

As users click on different nav links, the "currentpage" class transitions from one div to another, highlighting the active page.

The CSS for the body tag is as follows:

.video {
background: url(../img/video_bg.jpg);
background-size: cover;

}

I aim to modify the background image of .video depending on which page is active - #about, #services, #portfolio, etc.

TL;DR
I require assistance with implementing a code block that checks for a specific ID within a div that also contains a certain class, allowing me to customize the background image using CSS.?

Edit 2:
In order to address the issue, I devised a workaround strategy including the following steps:
1) Set the overall background color to #000, removed the original bg-image completely, and reintroduced a full-screen video that was previously hidden
2) Modified each nav menu item to include a hidevid class, except for the Home link which became showvid
3) Implemented CSS rules for each page ID (e.g., #about {background-image: url(image);}
4) Created a new CSS class: .hidethis {display: none;}
5) Used the following jQuery script:

$(document).ready(function(){
$(".hidevid").click(function(){
    $("video").addClass("hidethis");
});
$(".showvid").click(function(){
    $("video").removeClass("hidethis");
});

});

This approach resulted in capturing the essence of the desired effect by changing the background to black only visible when transitioning between pages while maintaining the video display on the landing ("home") page. Clicking on the navigation menu triggers the "slide" effect showing the respective background image and hiding the video element along with other contents represented by the nav menu against a black backdrop.

Answer №1

If you want to use vanilla JavaScript (pure JavaScript) to determine if a div contains a specific class and then make changes to the CSS accordingly, you can achieve this by following these steps:

var targetDiv = document.getElementById('target');
var backgroundDiv = document.querySelector('.background');

if (targetDiv.classList.contains('active')){ // Check if #target has the "active" class
    targetDiv.style.backgroundColor = 'blue';       // Change background color of the target div to blue
    backgroundDiv.style.backgroundImage = 'url(image-url-here)'; // Change the background image of the background div
}

Live Example: http://jsfiddle.net/JohnDoe56/xqvbnmzc/8/


Answer №2

Your code appears to be incorrect. The correct usage is as follows:

css('background-color','red')

Answer №3

I managed to find a creative solution for this issue. Here's what I came up with: 1) I adjusted the overall background color to #000, got rid of the original bg-image completely, and reintroduced a full-screen video that was previously hidden 2) I modified each navigation menu item to include a hidevid class, except for the Home link, which I changed to showvid 3) I customized CSS for each individual "page" ID (i.e., #about {background-image: url(image);} 4) I developed a new CSS class named .hidethis {display: none;} 5) Then, I incorporated the following jQuery script:

$(document).ready(function(){
$(".hidevid").click(function(){
    $("video").addClass("hidethis");
});
$(".showvid").click(function(){
    $("video").removeClass("hidethis");
});
});

This setup essentially sets the background as black, but only shows it on the main landing ("home") page along with the video. When clicking on a navigation menu item, the next "page" smoothly transitions into view, revealing its background image while hiding the video and additional content by applying a display: none property. This results in a sleek transition effect with just a black backdrop behind the navigation menu.

Answer №4

Based on the limited information provided, it seems that the issue lies in using CSS to cover the background. One possible solution is to transfer the initial background from the body to the #main div and adjust the padding for the .page-1, .page-2, etc. divs accordingly. Additionally, if the background images have transparency, consider adding a background-color.

Assuming that the navigation does not contain a background image and remains stationary. I'm also assuming that the section sliding functionality is already implemented but not shown here. The HTML structure has been left unchanged.

body {
  margin: 0;
  height: 100%;
}

nav {
  height: 50px;
  background-color: #ccc;
}

main {
  background-image: url(https://picsum.photos/200/300?image=0);
  background-size: cover;
}

.pt-perspective > div {
  height: calc(100vh - 50px);
  padding: 50px;
  background-repeat: no-repeat;
  background-color: aqua;
  background-size: cover;
  background-image: url(https://picsum.photos/200/300?image=0);
  display: none;
}

.pt-perspective .currentpage {
  display: block;
}

.pt-perspective .page-1 {
  background-image: url(https://picsum.photos/800?image=1);
}
.pt-perspective .page-2 {
  background-image: url(https://picsum.photos/800?image=2);
}
.pt-perspective .page-3 {
  background-image: url(https://picsum.photos/800?image3);
}
.pt-perspective .page-4 {
  background-image: url(https://picsum.photos/800?image=4);
}
.pt-perspective .page-5 {
  background-image: url(https://picsum.photos/600?image=5);
}
<body class="video">
<!-- <div class="preload">Whole lot of stuff in here for a preload overlay</div> -->
<nav>Nav is here</nav>
<main>
    <div id="pt-main" class="pt-perspective ">
        <div class="page-1 currentpage" id="main"></div>
        <div class="page-2" id="about"></div>
        <div class="page-3" id="services"></div>
        <div class="page-4" id="portfolio"></div>
        <div class="page-5" id="contact"></div>
    </div>
</main>

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

Disabling the close button on a particular Colorbox popup

Utilizing the colorbox plugin to showcase messages on my website, one of them being a "wait for response" message that I wish to prevent users from closing themselves. Although I'm able to unbind the ESC key and disable overlay close options, I still ...

Creating a new project in ASP Net Core Angular using Bootstrap 4 for the SideMenu layout instead of Bootstrap 3

I am currently working on developing a website using Angular6, where I aim to have a vertical navbar for large screens and a top navbar with dropdown functionality for mobile devices. While searching online, I came across several examples that seemed overl ...

Another option instead of using the "$ (document).ready" function

I have integrated fancybox into an ASPX page but encountered an issue where the document ready function is not functioning properly for the lightbox feature. I was advised to create a new JavaScript code specifically for loading the lightbox on that part ...

When using the Column width property in React Material UI, it may not automatically expand

I've been playing around with React Material UI Tables and I'm having trouble making the columns auto-expand without wrapping. I tried setting the 'width: auto' property in the <Table size="small" style={{ width: auto}}> ...

How can you utilize multiple files to set environment variables in Node.js?

My project has two different environments for development and production production.js var config = { production: { session: { key: 'the.express.session.id', secret: 'something.super.secret' }, ...

Unable to display content on page when using node.js and express

I have organized my controllers in the following manner... const Landmark = require('../models/landmark'); function indexRoute(req, res, next) { Landmark .find() .exec() .then((landmark) => res.render('/landmarks/index', { l ...

Achieving a bottom tab bar display exclusively on default screens within nested stacks in react-navigation

Suppose I have a Tab Navigator where each tab contains nested stack navigators (refer to the code snippet below). My goal is to have the tab bar visible only on the default screen of each nested stack, similar to how the current Twitter Android app operate ...

The way in which the DOM responds to adding or deleting elements from its structure

My typical method for displaying a popup involves adding an empty div tag and a button to the webpage: <div id="popupDiv"></div> <input type="button" id="popupButton" /> I then use jQuery to handle a button click event, make an ajax cal ...

What is the best way to transfer an element and all its children to another div without losing any jQuery functionality?

At first, sharing an example of the JavaScript and HTML from my page is challenging because I couldn't make it work on JSfiddle. The issue I'm facing involves jQuery on a page where I've created two tabs. Essentially, it's the same con ...

Using both jQuery and Ajax can result in multiple requests being sent when utilizing the focus

Hey there, I've got a form with around 20 input fields. My goal is to trigger an AJAX request every time a user moves from one field to another. Everything seems to be working fine, but there's a peculiar issue. Upon moving from one field to th ...

If the current PageName matches, jQuery will include an additional element

Currently dealing with a software that generates messy code, I am in search of a way to access a specific table cell based on the PageName (URL). The challenge lies in the fact that the pages are created dynamically without any class specifications in the ...

Issue with toggleClass not functioning properly after receiving data from an AJAX call

On my website, I have a link that triggers an AJAX request. However, when the response comes back and I try to use the toggleClass function in the following .js code snippet, it doesn't work as expected: $(document).ready(function(){ $("td").click( ...

Certain issues arise when adjusting the padding within the background color of solely the inline text element

Appreciate your time. I'm working on adding background color to the TEXT exclusively, and have successfully done so by styling .post-title { text-transform:capitalize; margin-top:4px; margin-bottom:1px; font-size:22px; background-color:#FFF; dis ...

Using PHP variables in JavaScript is not compatible

Currently, I am facing an issue where PHP variables inside the javascript code are not being echoed. When I try to echo the variables outside of the javascript, everything works perfectly fine. After carefully reviewing my code multiple times, I still cann ...

How can I transfer the value of a local variable to a function variable in Three.js JSON Loader?

I am attempting to import an external JSON model into the scene and assign its value to a variable called head, and then add it to the scene. This is what I have done: var loader = new THREE.JSONLoader(); this.head = loader.load( "eagle2.js", fu ...

Arrange the footers in the bootstrap card deck to be perfectly aligned at the top

Using bootstrap 4 to showcase cards has been successful, but there is an issue with footers that have varying content lengths. Instead of the footer adjusting its position based on the content, is there a way to keep the tops aligned while pushing the cont ...

Is it possible to use .jCarouselLite with multiple divs under the same name?

$("#gal-row").jCarouselLite({ vertical: false, hoverPause:false, visible: 5, auto:null, speed:1000, btnPrev:"#btn-next", btnNext:"#btn-prev", scroll: 5, circular:false }); I am lo ...

Why is my JQuery UI droppable accept condition failing to work?

After scouring the internet for hours, I'm still stuck and can't seem to figure out what's wrong with my code: Here's the HTML snippet: <ul style="list-style:none;cursor:default;"> <li>uuu</li> <li>aaa& ...

Divs that can be sorted are being shifted downwards within the swim lanes

JavaScript code snippet here... CSS code snippet here... HTML code snippet here... ...

Animate all shapes in SVG to rotate around a central pivot point

I am looking for a simple way to make an SVG graphic rotate around its center point. The rotation doesn't need to be smooth, just a 90 degree turn and back every second. https://i.sstatic.net/H6CTF.png Here is the SVG code: <?xml version="1.0" e ...