Home > Software engineering >  How does AND Operators in Javascript work?
How does AND Operators in Javascript work?

Time:12-14

Here is a snippet of some js code that I wanted to check the system time and display an image depending on the time of day. There are 4 images; the first should display between 6:00 and 10:00 the next from 10:00 - 14:00 and the third one from 14:00 - 18:00. After this till morning the default image displays.

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <title>ImageViewer</title>
  </head>
  <body>
    <script type="text/javascript" src="app.js" ></script>
    <img id='Kiss100' src="images/4.png">
  </body>
</html>

CSS

body {
    background-image:linear-gradient(white, dimgray);
}

img {
  width: 100%;
  height: auto;
}

Javascript

setInterval(function () {
  var imgEl = document.getElementById('Kiss100');
  if (!imgEl) return;
  
  var date = new Date();
  
    imgEl.src = date.getHours() >= 6 && <10
    ? "images/3.jpeg"
    : date.getHours() >= 10 && <14 
    ? "images/1.jpeg"
    : date.getHours() >= 14 && <18
    ? "images/2.jpeg"
    : "images/4.png";
}, 5000);

The problem is that I keep getting this error when I try to run: 'Uncaught SyntaxError: Unexpected token '<' (at app.js:7:41)'

CodePudding user response:

You need to check hours after using && again condition && condition

here is what I did with your code :

setInterval(function () {
  var imgEl = document.getElementById('Kiss100');
  if (!imgEl) return;
  
  var date = new Date();
  let hours = date.getHours()
  imgEl.src = ((hours  >= 6 && hours < 10
    ? "images/3.jpeg"
    : hours  >= 10 && hours < 14 )
    ? "images/1.jpeg"
    : hours  >= 14 && hours < 18)
    ? "images/2.jpeg"
    : "images/4.png";
}, 5000);

and I added some parantheses to make sure that condition are going to be checked in right way

CodePudding user response:

Try this one

setInterval(function () {
var imgEl = document.getElementById('Kiss100');
if (!imgEl) return;

 var date = new Date();

  imgEl.src = date.getHours() >= 6 && date.getHours() < 10
  ? "images/3.jpeg"
  : date.getHours() >= 10 && date.getHours() < 14 
  ? "images/1.jpeg"
  : date.getHours() >= 14 && date.getHours() < 18
  ? "images/2.jpeg"
  : "images/4.png";
 }, 5000);
  • Related