The toggle feature is failing to execute upon clicking the button with the onclick handler in JavaScript

const toggleButton = document.getElementById('btn');

setInterval(displayTime,1000);

toggleButton.onclick= function toggle() 
{
    if (toggleButton.innerHTML=="Light") {
        document.body.style.backgroundColor ="white";
        document.getElementById('hours').style.color = 'black';
        document.getElementById('minutes').style.color = 'black';
        document.getElementById('seconds').style.color = 'black';
        document.getElementById('session').style.color = 'black';
        toggleButton.innerHTML ="Dark";
        toggleButton.style.color ="white";
        toggleButton.style.backgroundColor ="black";
    } else {
        document.body.style.backgroundColor ="black";
        document.getElementById('hours').style.color = 'white';
        document.getElementById('minutes').style.color = 'white';
        document.getElementById('seconds').style.color = 'white';
        document.getElementById('session').style.color = 'white';
        toggleButton.innerHTML ="Light";
        toggleButton.style.color ="black";
        toggleButton.style.backgroundColor ="white";
    }
};

function displayTime(){};

How can I get this code to function properly? I attempted using addEventListener('click', toggle) instead of onclick, but it did not work. I want the timer to continue running, with the toggle function only activating when the specified button with the id "btn" is clicked.

Answer №1

give this a shot

toggleBtn.onclick = function() {
    if (toggleBtn.innerHTML=="Daytime") {
        document.body.style.backgroundColor ="lightgray";
        document.getElementById('hours').style.color = 'black';
        document.getElementById('minutes').style.color = 'black';
        document.getElementById('seconds').style.color = 'black';
        document.getElementById('session').style.color = 'black';
        toggleBtn.innerHTML ="Nighttime";
        toggleBtn.style.color ="white";
        toggleBtn.style.backgroundColor ="dimgray";
    } else {
        document.body.style.backgroundColor ="dimgray";
        document.getElementById('hours').style.color = 'white';
        document.getElementById('minutes').style.color = 'white';
        document.getElementById('seconds').style.color = 'white';
        document.getElementById('session').style.color = 'white';
        toggleBtn.innerHTML ="Daytime";
        toggleBtn.style.color ="black";
        toggleBtn.style.backgroundColor ="lightgray";
    }
};

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

What is the best way to trigger events upward in a Backbone View hierarchy?

Running a backbone app with a structured view system, here's a simplified version of how it looks: NewsListView = Backbone.View.extend({ el: $('li#newspane'), initialize: function() { _.bindAll(this); }, render: f ...

Is the for loop in Node.js completed when making a MySQL call?

A certain function passes an array named res that contains user data in the following format: [ RowDataPacket { UserID: 26 }, RowDataPacker { UserID: 4 } ] The goal is to create a function that fetches each user's username based on their ID and stor ...

Refresh State component following fetch using Redux

Greetings everyone, I'm currently in the process of learning React and Redux. I've encountered a challenge where I am unable to update the state of a specific container using Redux without resorting to a setTimeOut function due to the asynchronou ...

Transmit an HTML table to PHP

I have successfully created a dynamic table within a form, but for some reason, it's the only element that is not being fetched. To build this table, I utilized the bootstable framework which allows for easy creation of tables with interactive featur ...

I have created a Joomla Template that incorporates my own CSS through JavaScript. Is there a method to include a distinct version tag to my custom CSS file, such as custom.css?20180101?

My usual method involves adding a unique tag to the css path in the html section, but my template is incorporating custom CSS through Javascript: if (is_file(T3_TEMPLATE_PATH . '/css/custom.css')) { $this->addStyleSheet(T3_TEMPLATE_URL . &apo ...

Utilizing JavaScript text variables as hidden inputs

My JavaScript code is responsible for populating a modal from various sections of a website. Essentially, when the modal expansion button is clicked, it collects all data associated with that particular button press. While this functionality works flawles ...

Storing Radio Buttons and Checkboxes Using LocalStorage: A Simple Guide

Is there a way to save and retrieve values from localStorage for input types "radio" and "checkbox"? I've tried using the same code that works for text and select elements, but it doesn't seem to be saving the values for radio and checkbox. Can s ...

Discovering the way to retrieve background height following a window resize using jQuery

Is there a way to obtain the background height once the window has been resized? div { background-image: url(/images/somebackground.jpg); background-size: 100% 90%; background-repeat: no-repeat; width: 70%; background-size: contain; ...

Unlocking the secrets to obtaining a socket.io client

I encountered an error when trying to set up a socket.io server and client. The error I received on the client side was: Failed to load resource:http://localhost:3000/socket.io/?EIO=4&transport=polling&t=OK-egu3 the server responded with a status o ...

Issue with fadein() function not executing properly when placed in a separate JavaScript file

Background of the Question In a simple scenario, a user submits a form which then adds a spinner GIF to a div. The Problem: When I include the jQuery and JavaScript code in the page inside <script> tags, everything works fine. However, if I place ...

Setting the default TAB in a specific Menu Tab within the Menu Bar

I'm encountering some issues with this code. Specifically, the menu bar JavaScript is automatically clicking on the Second TAB instead of the First TAB when run. JS CODE. var dolphintabs = { subcontainers: [], last_accessed_tab: null, ...

Ensure that the form is submitted when a checkbox is clicked, while also maintaining the native browser

My form contains a text input field and a checkbox. The text input must not be left empty when the form is submitted, which is why the required attribute is used. I want the form to be submitted every time the checkbox is clicked, while still maintaining ...

Ways to utilize the map() function with data retrieved from an axios response?

Utilizing axios for data retrieval from the server and then storing it in the state. However, when attempting state.map( post => {console.log(post)} ), no output is displayed. The technologies being used are Express, Mongoose, NextJS, and Axios. My ap ...

Tips for stopping html form from refreshing upon submission

Hello, despite extensive searching and testing, I am still unable to locate the issue and therefore I am reaching out to seek your assistance in resolving my problem. Within a form that I have created, upon clicking the submit button, a javascript functio ...

JavaScript was unable to locate the requested URL on the server

After successfully deploying and accessing the URL using Firebase's hosting feature, everything seems to work fine. However, when I try to access a specific endpoint like this: https://*******.web.app/api/send, I encounter the following error message: ...

Enhance hover effects with JQuery through dynamic mouse movements

$(document).ready(function() { $(".hoverimage").hover( function(e) { updateCoords(this,e); openQuicktip(this); }, function() { closeQuicktip(); } ); $("area").hover( function(e) { updateCoords(this,e); openQuicktip(this); }, function ...

Using the .json method in Angular 7 for handling responses

While attempting to implement the function getProblems to retrieve all problems within its array, I encountered an error message appearing on res.json() stating: Promise is not assignable to parameters of type Problem[]. It seems that the function is ...

Navigate back to the parent directory in Node.js using the method fs.readFileSync

I'm restructuring the folder layout for my discord.js bot. To add more organization, I created a "src" folder to hold all js files. However, I'm facing an issue when trying to use readFileSync on a json file that is outside the src folder. Let&ap ...

Determine the dimensions of Expo's React Native Over the Air (OTA) update

Is there a method to determine the size of the required download for an OTA update before existing deployed apps (e.g. v1) retrieve it following the publication of a new managed Expo app (e.g. v2)? ...

Why are JavaScript errors constantly popping up when I use Django Pipeline?

After configuring Django Pipeline (version 1.3.15) for a specific group of JS files, I ensured they were in the correct order based on their appearance on my page. The collectstatic process went smoothly and when viewing the source, it looked like all th ...