Altering the background image according to the time of day

I have a "section" element with a background image included.

<section id="header" class="color-light text-center" data-type="background" data-speed="10">

This is the CSS styling for the header section:

#header {
    background: url('sunrise.jpg') 50% 0 no-repeat fixed;
    height: 800px;
    margin: 0;
    overflow: hidden;
    color: #f4f4f4;
}

Using JavaScript to determine the time of day...

var d = new Date();
var n = d.getHours();
if (n > 19 || n < 6)
    $("#header").className = "night";
else if (n > 16 && n < 19)
    $("#header").className = "sunset";
else
    $("#header").className = "day";

The CSS file contains classes for different times of the day, but unsure on implementation:

/* backgrounds */
.day { background: url('sunrise.jpg') 50% 0 no-repeat fixed; }
.sunset { background: url('sunset.jpg') 50% 0 no-repeat fixed; }
.night { background: url('night.jpg') 50% 0 no-repeat fixed; }

Uncertain about properly changing the #header using jQuery to update the background dynamically.

Answer №1

Follow these steps to ensure success.

let today = new Date();
      let timeNow = today.getHours();
      if (timeNow > 19 || timeNow < 6)
        $("#header").css("background", "url('night.jpg')");
      else if (timeNow > 16 && timeNow < 19)
        $("#header").css("background", "url('sunset.jpg')");
      else
        $("#header").css("background", "url('day.jpg')");

Answer №2

Class, when referring to jQuery objects, cannot be accessed directly as a property. To modify a property on a jQuery object, it is recommended to use .prop(). However, in the case of dealing with classes, you can easily utilize .addClass(), .removeClass(), and .toggleClass(). For more information, visit: https://api.jquery.com/category/manipulation/class-attribute/

If no other issues arise from the code, the following snippet should function as intended:


var now = new Date();
var currentHour = now.getHours();

if (currentHour > 19 || currentHour < 6)
    $("#header").addClass("night");
else if (currentHour > 16 && currentHour < 19)
    $("#header").addClass("sunset");
else
    $("#header").addClass("day");

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

Limiting the use of CSS selectors to a single class without the need to include the class name multiple

I am trying to find a solution to avoid repeating the same class name multiple times in CSS. For instance, if I have: .class1 div { color: red } .class1 h2 { color: blue } .class1 p { color: yellow } Is there a way to consolidate these three rules under ...

Changing the link color within a repeater in ASP .NET when it is clicked

The given code snippet is being executed on an iPhone 4, causing some CSS elements like Hover to not function as expected. <asp:Repeater ID="rpt" runat="server"> <HeaderTemplate> <div class="table withshadow"> </Header ...

Attach the JSON data to the dropdown menu using jQuery

On my asp.net website, I have generated a JSon string using the JavaScriptSerializer class in JavaScript. Then, I displayed the Json string within the HTML markup by utilizing the RegisterStartupScript method and here is how it appears: This is the C#.net ...

What determines the functioning of the "N-in-one" or "pill" button effect?

I am interested in incorporating a style element known as the "pill" button, which can be found by visiting the following link: http://jqueryui.com/themeroller/ (specifically the "Choice 1 | Choice 2 | Choice 3" widget) Refer to the screenshot below: To ...

How can I align one div in the vertical center while keeping another div in its original

I need help! How can I vertically center the .tagline-container within a div that has two children divs, without affecting the positioning of the nav? <div class="header"> <nav class="navbar"> <h1>Rainey 13 F ...

Invoking PHP function within a specific class using Ajax

I am currently utilizing Zend Framework. My PHP class is structured as follows: FileName : AdminController.php Path : /admin/AdminController.php Ajax Function : function exportToExcel() { $.ajax({ url: "/admin/AdminController/testFunction", ty ...

Is there a way to conceal a div that holds a full table when the table consists of only one row?

I am relatively new to working with JS and HTML. I have attempted to use the following function, but unfortunately, I am not seeing any results. Any assistance would be greatly appreciated. Below is the JavaScript code as well as the HTML div and table whe ...

Design a Logo-aligned Header using Bootstrap 4 for a professional and sleek look

I'm attempting to design a header using bootstrap 4 that resembles the image shown https://i.sstatic.net/MFVZU.png. However, I'm encountering several issues with this method. The main problem is that the logo is not properly centered in the middl ...

on document load, ensure that the button containing class x is hidden

I am currently using the Kendo Custom Command feature in my application to display an Add button with each record. When a user clicks on the Add button, I want the program to replace it with a Remove button. Initially, I struggled to achieve this using doc ...

Enlarge the div with a click

I was looking for a solution on how to make a div expand when clicked using jQuery I came across a tutorial that seemed simple and perfect, but I couldn't get it to work when I tried to replicate the code. Do you know if this code is still valid wit ...

Creating a sticky footer with CSS: A step-by-step guide

Struggling to keep my footer at the bottom of the page, I attempted this code: position: absolute; left: 0; bottom: 0; height: 100px; width: 100%; Unfortunately, my footer ended up looking messy. My website runs on WordPress, and ideally, I'd like t ...

What is the method to display HTML code using JavaScript within a span element in a JSP page?

While working on a jsp file, I came across a span tag with the following code: <span id="divBasicSearchResults" style="height:100%;"></span> Below is the Javascript function that generates HTML content for this span: function renderBasicSear ...

Creating a row with 5 columns in Bootstrap 4 dynamically is a handy trick for enhancing the layout of your website

Struggling to find the right layout for displaying products on my store's home page. <div class="row"> @foreach($produts as $product) //this is the syntax of my templating engine <div class="col-md-3"> </div> @endf ...

How can I implement a while loop for this animation using Javascript?

I've been delving into the world of JavaScript for a few days now, but I've hit a roadblock when it comes to implementing a while loop/switch statement in this animation project. The idea behind the program is that the image will "level up" and ...

The span created by jQuery does not automatically focus on the lightbox image

I am currently working on a jQuery script that generates a lightbox span when the drop-down menu is changed. My objective is to display an image when the drop-down menu changes and allow users to click on the image to open the lightbox on the screen. The ...

What is the best way to create floating content over a fixed video using HTML?

On the webpage, there is a background video set with position: fixed. Below the video, there is a <div> containing the main content. How can I make this content float over the video? Check out my experimental page at oleg-s-fresh-site-8f277a.webfl ...

Implementing the History API to dynamically load content into a div using Ajax

On my WordPress site, I have post content that loads into a div using AJAX when a user clicks on it. Now, I'd like to update the URL for the current post without using hashes. How can I achieve this with my JavaScript? JavaScript: jQuery(docum ...

In the realm of JavaScript, the GET request exclusively functions in Internet Explorer

This particular request is specific to Internet Explorer. I've spent the last two days attempting various solutions to make it work, but unfortunately, I have not been successful. Any advice would be greatly appreciated. Pure JavaScript: var xm ...

Changing URL parameters without refreshing the page using query strings

Is there a method similar to how Google adds and removes parameters from the URL in Gmail without requiring a postback? For example, when you start composing a draft, a "?compose=new" parameter is added to the URL. I was considering using `history.pushSta ...

Executing Python script via AJAX or jQuery

I need to execute Python scripts from JavaScript. The goal is to provide an input String to the Python script as an argument and then showcase the output on our webpage. Below is the Python code that runs smoothly on my Linux box: ./sample.py 12345 produc ...