Using jQuery to change opacity depending on the time of day

I've been developing an open source project named BitDay that originated from a Reddit thread some time ago.

In this project, I have 12 CSS classes representing different elements, each with its own unique background image.

Currently, the jQuery script I wrote fetches the current time and dynamically changes the background image based on the time of day. This means that every 2 hours, the background will transition to a new image.

$(function() {
  // JavaScript code here...
});

#container {
    // CSS styles here...
}

.bg {
    // Background styles here...
}

/* Define background images for various times of the day */
<div id="container">
    <div class="bg-splash"></div>
    <div class="bg-tobe" style="display: none;"></div>
</div>

Instead of instantaneously changing the background image depending on the hour, I'm looking to implement a gradual transition effect. For example, at 7am, bg-1 will be fully visible at 100% opacity. As time progresses, it will slowly fade into bg-2, reaching full opacity by 8am. This fading effect will continue throughout the morning, creating a smooth transition between backgrounds over the course of 2 hours.

Furthermore, I aim to make this transition persistent for all users accessing the start screen. This means that if a user logs in at 8:30am, they will see bg-1 displayed at 25% opacity, seamlessly blending into bg-2.

I'm grappling with the implementation details on this feature and would greatly appreciate any assistance or insights!

Answer ā„–1

After careful consideration, I have decided to introduce a new solution while preserving the existing one above. The new approach offers a different functionality compared to the more intricate answer below.

In response to your request for a "kicker" feature, I have successfully integrated this enhancement. Now, when transitioning between two backgrounds (referred to as "time blocks" in the code comments), the fading will commence midway. Below is the revised code implementation:

It is important to note that due to technical constraints, I had to adjust the background timings to fixed 2-hour intervals (refer to the bottom of the JavaScript code). This alteration may result in the backgrounds deviating from real-life sunset and dawn durations. Creating variable background durations, ranging from 1 to 4 hours, would necessitate extensive coding efforts. I trust this compromise is acceptable.

The timer interval has been set at 7200000 milliseconds (2 hours). To verify its functionality, please inspect the console log and background images using Inspect Element. A sample log output illustrates the current status, indicating the opacity levels of the starting backgrounds:

CURRENT TIME IS: 14:59. STARTING BACKGROUNDS ARE: bg-6 (opacity 0.01, fading OUT); bg-7 (opacity 0.99, fading IN).

Three minutes later, the transition will progress to fade out bg-7 and fade in the subsequent background, bg-8:

CURRENT TIME IS: 15:02. STARTING BACKGROUNDS ARE: bg-7 (opacity 0.98, fading OUT); bg-8 (opacity 0.02, fading IN).

I am eager to witness the final outcome, and should you choose to acknowledge my contribution in the credits, I would be grateful. Best of luck with your project!

Additionally, here is the updated fiddle link: https://jsfiddle.net/LaurensSwart/2go9g5n5/1/

(JavaScript code block)
(CSS code block)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bg" id="backgroundOne">

</div>
<div class="bg" id="backgroundTwo">

</div>

Answer ā„–2

Here you go! Make the 2000ms into 7200000 to create a gradual fade effect over a span of 2 hours. Additionally, I've shared it on Fiddle: https://jsfiddle.net/pbfuauzg/3/

I've been experimenting with adjusting the timing between the setInterval() and fadeIn() periods. Currently, I found that setting the fade() duration slightly shorter than the setInterval functions (e.g. 500 milliseconds) yields optimal results. Check out the code below for reference.

I've also tidied up your CSS by eliminating repetitive code sections. Can I please have a cookie now? :D?

Please remember: the time interval between each background isn't precisely 2 hours in your script (e.g. you have backgrounds set for 15:00h and 16:00h). To achieve perfect execution, adjust these timings to have regular 2-hour intervals instead of alternating between 1-hour and 3-hour intervals!

var timeBetweenBackgrounds = 2000; // in milliseconds - modify this to 7200000 for 2 hours

var d = new Date();
var hour = d.getHours();
var bgNumber = getPicture(hour);

$(document).ready(function() {

  $('#backgroundOne').addClass('bg-' + bgNumber);

  setBackground();
  window.setInterval(setBackground, timeBetweenBackgrounds);

});

var activeBackground = bgNumber;
var activeDiv = 1;

function setBackground() {

  if (activeDiv == 1) {

    if (activeBackground < 11) {
      var nextBackground = activeBackground + 1;
    }
    if (activeBackground == 11) {
      var nextBackground = 0;
    }
    console.log('Current background = ' + activeBackground + '. Next background = ' + nextBackground + '. Fading out container One. Fading in container Two.');
    $('#backgroundTwo').attr('class', 'bg').addClass('bg-' + nextBackground).fadeIn(timeBetweenBackgrounds);
    $('#backgroundOne').fadeOut((timeBetweenBackgrounds-500), function() {
      activeBackground = nextBackground;
      activeDiv = 2;
    });

  }
  if (activeDiv == 2) {

    if (activeBackground < 11) {
      var nextBackground = activeBackground + 1;
    }
    if (activeBackground == 11) {
      var nextBackground = 0;
    }
    console.log('Current background = ' + activeBackground + '. Next background = ' + nextBackground + '. Fading out container Two. Fading in container One.');
    $('#backgroundOne').attr('class', 'bg').addClass('bg-' + nextBackground).fadeIn(timeBetweenBackgrounds);
    $('#backgroundTwo').fadeOut((timeBetweenBackgrounds-500), function() {
      activeBackground = nextBackground;
      activeDiv = 1;
    });

  }

}


//Determines the picture to use based on the hour
function getPicture(hour) {
  if (hour >= 23 || hour <= 2)
    return 11;
  else if (hour >= 22)
    return 10;
  else if (hour >= 21)
    return 9;
  else if (hour >= 19)
    return 8;
  else if (hour >= 16)
    return 7;
  else if (hour >= 15)
    return 6;
  else if (hour >= 13)
    return 5;
  else if (hour >= 12)
    return 4;
  else if (hour >= 10)
    return 3;
  else if (hour >= 7)
    return 2;
  else if (hour >= 5)
    return 1;
  else
    return 0;
};
body {
  overflow: hidden;
}

.bg {
  width: 100vw;
  height: 100vh;
  position: absolute;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: 99;
  opacity: 0.7;
}

.bg-0 {
  background-image: url("http://i.imgur.com/qexylYA.png");
}

.bg-1 {
  background-image: url("http://i.imgur.com/cRvIYLJ.png");
}

.bg-2 {
  background-image: url("http://i.imgur.com/UusvZC8.png");
}

.bg-3 {
  background-image: url("http://i.imgur.com/URjIjZS.png");
}

.bg-4 {
  background-image: url("http://i.imgur.com/Fy7kANa.png");
}

.bg-5 {
  background-image: url("http://i.imgur.com/e2lvJ8q.png");
}

.bg-6 {
  background-image: url("http://i.imgur.com/JEslGSe.png");
}

.bg-7 {
  background-image: url("http://i.imgur.com/v2h0qzb.png");
}

.bg-8 {
  background-image: url("http://i.imgur.com/xyfqUsX.png");
}

.bg-9 {
  background-image: url("http://i.imgur.com/XbIlhvL.png");
}

.bg-10 {
  background-image: url("http://i.imgur.com/xDAIc6P.png");
}

.bg-11 {
  background-image: url("http://i.imgur.com/kaCxCBi.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bg" id="backgroundOne">

</div>
<div class="bg" id="backgroundTwo" style="display: none;">

</div>

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

Creating visuals from written content

I am attempting to transform Y[0] into an image rather than text. Currently, it is only displayed as a plain text link and not as an image. <html> <head> <script type="text/javascript"> function modifyContent(){ var rows=document.g ...

Using jQuery each, the output is an undefined Object or HTMLElement

Using jQuery's each/getJSON to iterate through a data.json file, collect and format the data, and display it on the page within the #output div. The functionality is working correctly, except for the unexpected addition of [object HTMLElement] that a ...

Display subpages of WordPress site in a dropdown menu on the navigation bar

Currently in the process of converting an HTML website to Wordpress, I am encountering a challenge. The issue lies in my attempt to add a drop-down feature to the navigation list using the wp_list_pages tag. As it stands, when hovering over the "products" ...

The button will remain inactive until a selection is made from the drop-down menu, following Material

Is there a way to use Material Design css and jquery to disable the next button until a value is selected from a drop down list? <div class="mdl-selectfield mdl-js-selectfield"> <select class="mdl-selectfield__select" id="ad_duration"> ...

"Major issues arise as CSS3 Animation fails to function properly across all web

I have been experimenting with using a sprite and CSS3 animation to create a rollover effect. While it seems to be working in CODA 2, I'm encountering issues when testing in Mozilla, Chrome, Safari, and Opera as the animation fails to trigger. /*link ...

What is the best way to ensure a div stays inline with the main product box?

https://i.sstatic.net/KM3T2.png https://i.sstatic.net/tcUDg.png .product-row { margin: 0px 0px 0px 0px; } .product-box { display: flex; flex-direction: column; width: 300px; padding: 15px; margin: 0px 26px; position: relati ...

Is it possible to implement jQuery events on all elements belonging to a specific class

Hey there, I'm facing a little challenge with my code. Currently, I have a snippet that allows a user using iOS to drag around a <div> with the class .drag on the webpage. Everything works perfectly when there's only one instance of .drag, ...

CSS division style not being properly implemented across entire form

I currently have an HTML form linked to a CSS file. Here is the HTML code: .css-form-group{ margin-bottom:10px; clear:both; } .css-form-group label{ font-weight: bold; } .form-input{ float: right; } .form-input:focus{ background: y ...

Combining arrays into an Object with zipped keys and values

I have some data that I am working with var foo = ['US','MX','NZ']; var foo1 = [12',13',17]; var Object = {}; I attempted a solution by doing the following var Object = {foo:foo1} Unfortunately, this approa ...

Ways to ensure that input text is fully cleared, even if it is set to empty

I am facing an issue with multiple input fields, some are pre-filled with default values while others are left empty and filled dynamically with a select value. Upon selecting an option from the dropdown, the chosen value is populated into the input field ...

Utilizing JSON to enhance Jquery Autocomplete with custom parameters

My goal is to create an autocomplete input field where, as a user types a letter, the value of the field is sent to the server and words that match are returned. var acOptions = { source:function (request, response) { $.ajax( ...

Placing an icon and a title on the same baseline

I'm working on a new website design and I really like the layout shown in this image: https://i.stack.imgur.com/QuVRZ.png I've been struggling to align the icon with the title in a responsive manner. Here are some of the approaches I've att ...

Angular - The connections between deeply nested object models are established

I have an Angular application that is used to display company and contact person information in a text box format. Here is the code for displaying the Company Email address: <label> Company Email address</label> <input type="text& ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Tips for showing an inline <span> within <div> elements

Is there a way to showcase inline spans within a div element while ensuring they are displayed equally in size and space, based on the user's screen? And how can I ensure that these spans are positioned behind other div elements? body { width: au ...

Dropping down with Twitter Bootstrap's navbar menu

Iā€™m currently facing some challenges with getting the Twitter Bootstrap drop-down navbar feature to function properly. Despite going through various tutorials, I am unable to make it work by directly copying the code. The console displays the following e ...

A guide on creating a clickable polygon in Vue.js using Konva

Is there a way to create an interactive polygon in Vue Konva where I can set each corner with a click? I haven't been able to find any resources other than the v-polygon which only creates predefined polygons. ...

Adjusting Position for Parallax Effect using Jquery

I am currently experimenting with a basic Scrolldeck Jquery Parallax effect to scroll items at varying speeds. However, I am encountering some difficulties in making items move from top to bottom. In the example provided below, you will see a shoe moving f ...

Acquiring the PayPal callback variable with PHP

When using PayPal Standard HTML form, upon completion of the transaction, the user is directed to the return URL. To retrieve variables such as the user email, order number, and other available information using PHP, I need to utilize the GET method from t ...

The TypeAhead feature fails to display any search results for the entered query

Feeling really desperate right now! I'm facing a frustrating issue with Bootstrap Typeahead. Here is the HTML Markup: <div class="form-group"> <label for="">Recipients</label> <input id="recipients" name="recipients" ...