What is the reason for not being able to utilize the same ID more than once?

This snippet of code may not be complete, but it effectively addresses the issue at hand.

<body onload="init()">
    <nav>
      <h1 style="font-family:Helvetica;">
        <ul class="nav">
          <li ><a href="#">Menu 1</a>
            <ul>
              <li id="navbar-menu"><a href="#">Sub-menu Item 1</a></li>
              <li id="navbar-menu"><a href="#">Sub-menu Item 2</a></li>
              <li id="navbar-menu"><a href="#">Sub-menu Item 3</a></li>
            </ul>
          </li>
        </ul>
      </h1>
    </nav>
<body>

There are a total of 4 menus in this code.

.nav li ul a:hover {
   background: rgb(96, 235, 245);
    color:white;
  }

body {

    color:white;
  }

When I hover over the sub-menu items, the background color changes. However, I want this color change to be based on the time of the user. I have attempted to implement this using JavaScript and have encountered issues. Below is the JavaScript code I am using:

function init() {
  function setBackgroundForTimeOfDay() {
    const body = document.querySelector('body');
    const hours = new Date().getHours();

    if (hours < 6 || hours >= 18)
      body.style.background = 'linear-gradient(to right, rgb(39, 38, 38), rgb(245, 96, 96),rgb(39, 38, 38))';

    else
      body.style.background = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 235, 245),rgb(39, 38, 38))';
  }
  setBackgroundForTimeOfDay();
  setInterval(setBackgroundForTimeOfDay, 60000);
}

function init1() {
  function setBackgroundForTimeOfDay() {
    const li = document.getElementById('navbar-menu');
    const hours = new Date().getHours();

    if (hours < 6 || hours >= 18)
      li.style.background = 'rgb(245, 96, 96)';

    else
      li.style.background = 'rgb(96, 235, 245)';
  }

  setBackgroundForTimeOfDay();
  setInterval(setBackgroundForTimeOfDay, 60000);
}
init1();

I am encountering issues with the JavaScript implementation. Can someone please provide insight on what the problem might be?

Answer №1

It may not be entirely clear what your intentions are, but a critical mistake to note is that you should not assign the same ID to multiple elements, as each ID must be unique! Consider using a class instead and adjust the logic as follows:

function init1() {
  function setBackgroundForTimeOfDay() {

    //_______________ getElementById ______________________
    var li = document.getElementsByClassName('navbar-menu');

    const hours = new Date().getHours();


    //_______________ and loop through li ___________
    if (hours < 6 || hours >= 18)
        for (var i=0; i < li.length; i++) {
          li[i].style.background = 'rgb(245, 96, 96)';
        }

    else
        for (var i=0; i < li.length; i++) {
          li[i].style.background = 'rgb(96, 235, 245)';
        }
  }

  setBackgroundForTimeOfDay();
  setInterval(setBackgroundForTimeOfDay, 60000);
}

Check out the revised example here: http://jsfiddle.net/gah909cd/

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

Combining href into click events - a step-by-step guide

I have an href link available. '<a href="index.php?imei=' + value['imei'] + '&nama=' + value['nama'] + '" class="summarykapal">Summary</a>' This is the function in question: function retr ...

Styling CSS for Centering a Heading on an Image's Center

Struggling to center an h3 heading in the middle of an image within a grid? Look no further, as I have 3 images across one row - four columns per image/heading. Check out the desired layout https://i.stack.imgur.com/8VFRt.png I've managed to center t ...

Ensure the validation of numerous input fields within a single form with the use of Vue 3 composition API

Within my application, I have implemented custom validation and validators to ensure the accuracy of various form fields. The submit button functionality is designed to remain disabled until all input fields are filled. The creation of validators involves ...

Enhancing PHP calendar functionality to accurately detect days in upcoming months

Looking to enhance a PHP calendar script, everything seems to be functioning correctly except for displaying days from the next months which are not appearing on the grid. I've attempted to troubleshoot the issue myself with no luck, so I would greatl ...

Retrieving the source code of a specific http URL using JavaScript

Is it feasible to obtain the source code of a webpage using JavaScript on the client side? Perhaps with AJAX? However, can I ensure that the server from which I am downloading the URL sees the client's IP address? Using AJAX could potentially reveal ...

Exploring the impact of naming variables in JavaScript versus not naming them

"use script"; var user = { name: "John Doe", career: "Civil Engineer", socialMedia: { fb: "www.facebook.com/johndoe", twitter: "www.twitter.com/johndoe" }, about: function() { console.log("My name is " + this.na ...

Transfer numerical values from PHP to JavaScript using individual files

What is the best way to pass variables from PHP to JavaScript when they are in separate files? Is it possible to achieve this without using AJAX, or is AJAX necessary for this task? If AJAX is required, how can I implement it? test.php <?php $a = 5; $ ...

What steps can be taken to prevent a wrapper's CSS from affecting its enclosed elements?

My container div includes some opacity and auto height that I don't want to affect all elements within it. Is there a way to preserve the container's styles without impacting its contents? ...

Transfer JSON data from Python Requests to JavaScript within Django views.py

I have a Python script that retrieves JSON data and parses it: from django.http import HttpResponse import json, requests def fetch_data(request): context = {} platformUrl = 'https://www.igdb.com/api/v1/platforms' platformReq = requ ...

The passing of React parent component props to the child component is not functioning as expected

Retrieving data through an ajax call and saving it to the state of the component _fetchDataFromServer(){ reqwest({ url: 'http://127.0.0.1:8000/api/example/' , type: 'json' , method: 'get' , contentType: &ap ...

The page fades in as soon as it is loaded thanks to the "

I am interested in creating a unique effect where different classes fade in on page load. Check out this webpage for reference. The linked page showcases squares in various shades of grey and color, with the desire to have them fade in at different inter ...

Looking for assistance in setting up a personalized slideshow to automatically play on its

Recently, I have taken responsibility for a project that was initiated by someone else. The website contains a customized slideshow on its homepage. To meet the client's requirements, I have already made some alterations to the appearance and feel of ...

I am having trouble debugging the Twitter Bootstrap v4-alpha grid. The col-sm-offset-* class doesn't seem to be

Something has been altered somewhere, causing col-sm-offset-*s to stop functioning entirely. For instance, when attempting to split the screen in half and only display content on the right side, I typically would use: <div class="container"> < ...

JavaScript list in Google Docs

I am a beginner in the world of the Google Docs API and I am interested in retrieving a list of all documents that are not spreadsheets using the Google Docs API. I have found an API that allows me to access a specific document when I provide its documentI ...

How to create flexible, non-url-changing layout states with angular-ui-router?

My Objective I am working with two different styles of display: "Normal": [ Header | Body | Footer ] - primarily used for most views "Discreet": [ Body ] only, centered on screen - ideal for states like login/register, errors etc. These display styles ...

Ways to restrict access to resources

My static website is simple, but I am concerned that everyone has access to my assets. For example, when I go to www.mysite.com/assets in the browser, it shows: Index of /assets Parent Directory css/ img/ js/ Is there a way to display a 403 error page ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Aligning the Navigation Bar to the Upper Right Corner

I'm attempting to rearrange my Nav Bar to be at the Top Right, with my logo on the Top Left all in one line. Unfortunately, I'm struggling to achieve this and could really use some guidance. As a newcomer to HTML and CSS, I find it challenging to ...

What are the steps to make the chosen title and its content active while deactivating the others?

I am currently developing a website for an educational institution that includes schools with subdivisions such as matric, CBSE, and state board, as well as a college. My goal is to create a user interface where clicking on a specific stream (such as matri ...

Adding a QR code on top of an image in a PDF using TypeScript

Incorporating TypeScript and PdfMakeWrapper library, I am creating PDFs on a website integrated with svg images and QR codes. Below is a snippet of the code in question: async generatePDF(ID_PRODUCT: string) { PdfMakeWrapper.setFonts(pdfFonts); ...