Home » Jquery » javascript – Need help in coding night mode wordpress webiste which will automatically trigger based on 7pm to 7am (Like instagram) but for my website

javascript – Need help in coding night mode wordpress webiste which will automatically trigger based on 7pm to 7am (Like instagram) but for my website

Posted by: admin February 22, 2020 Leave a comment

Questions:

I want to have a javascript code which checks if current time is between 7pm and 7am. If so it should change the background color on my website to X. If the current time is not between 7pm and 7am the background color should be the original of the wordpress theme. The time should be automatically known from the users browser and according to that the function should trigger.

I saw this code online it triggers users time

<script type="text/javascript" src="<?php echo plugin_dir_url( __FILE__ ) . 'moment.min.js';?>"></script>
<script type="text/javascript" src="<?php echo plugin_dir_url( __FILE__ ) . 'moment-timezone.js';?>"></script>
<script type="text/javascript" src="<?php echo plugin_dir_url( __FILE__ ) . 'moment-timezone-data.js';?>"></script>
<script type="text/javascript" src="<?php echo plugin_dir_url( __FILE__ ) . 'jquery-1.9.0.min.js';?>"></script>
<script type="text/javascript" src="<?php echo plugin_dir_url( __FILE__ ) . 'jstz-1.0.4.min.js';?>"></script>

<script type="text/javascript">
$(document).ready(function() {
  var tz = jstz.determine();
  var current_time= moment.tz().format('MMMM Do YYYY, h:mm:ss a');;
  alert(current_time);
});

the files needed to trigger the time
Download the necessary files

If you have any other method feel free to suggest

How to&Answer:

This should be pretty straightforward with some basic javascript and jquery:

$(document).ready(function() {

   // get today's info

   var d = new Date();

   // get the hour of the day - between 1 & 24

   var time = d.getHours();

   if (time >= 19) { 

     $('.background').css('background-color', '#000');

   } else if (time <= 7) {

     $('.background').css('background-color', '#000');
   }

)};