switching the content of an element using Javascript

I'd like to switch between two icons when clicking on .switch and apply the style of .nightTextNight to .nightText, my JavaScript code is working well everywhere except here.

Is there a simpler way to achieve this? I currently have to create two classes and give them an ID for every small change.

var nightBtn = document.getElementById("switch");
var body = document.getElementById("body");
var header = document.getElementById("header");
var navbar = document.getElementById("navbar");
var nightText = document.getElementById("nightText");

function nightMode() {
nightBtn.classList.toggle("switchNight");
body.classList.toggle("night");
navbar.classList.toggle("navbarNight");
nightText.classList.toggle("nightTextNight");
if(nightText.className = "nightTextNight") {
nightText.innerHTML = "<i class='fa fa-sun-o' aria-hidden='true'></i>";
} else {
nightText.innerHTML = "<i class='fa fa-moon-o' aria-hidden='true'></i>";
};
}
body {
background-color: white;
transition: background-color ease 0.3s;
padding: 0;
margin: 0;
font-family: sans-serif;
}

.night {
background-color: #3f4b5e;
transition: background-color ease 1s;
}

.switch {
height: 35px;
width: 35px;
border-radius: 50%;
background-color: #092d30;
border: 3px solid wheat;
float: right;
z-index: 4;
transition: background-color ease 1s;
margin-top: 12px;
margin-right: 4px;
cursor: pointer;
text-align: center;
line-height: 17.5px;
position: relative;
}

.switchNight {
background-color: wheat;
border: 3px solid #092d30;
z-index: 4;
transition: background-color ease 1s;
}

.textNight {
color: white;
}

.switch:hover {
background-color: #4d5e77;
transition: background-color ease 1s;
}

.switchNight:hover {
background-color: #fff2d8;
transition: background-color ease 1s;
}

/* --------------------- NAV BAR ------------------ */

.navbar {
width: 100%;
height: auto;
background: #f4f7f9;
position: fixed;
margin-top: 0;
padding: 0;
border-bottom: 3px solid #2fb3f9;
}

.navbar li {
list-style-type: none;
display: inline;
height: auto;
}

.navbar li a {
padding: 20px 25px;
text-decoration: none;
display: inline-block;
font-size: 20px;
font-weight: bolder;
color: #516f7f;
}

.navbar li a:hover {
color: #ff9d00;
transition: color ease 0.3s;
}

.navbarNight {
background-color: #556bb5;
border-bottom: 3px solid white;
}

.navbarNight li a {
color: white;
}

.nightText {
position: absolute;
color: white;
font-weight: bolder;
top: 9px;
right: 12px;
}

.nightTextNight {
color: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<title>Night Mode - TEST</title>
</head>
<body id="body">
<div id="container">
<div id="nav">
<ul id="navbar" class="navbar">
<li><a href="#">Home</a></li>
<li><a href="#">About me</a></li>
<li><div id="switch" class="switch" onclick="nightMode()"><span id="nightText" class="nightText"><i class="fa fa-moon-o" aria-hidden="true"></i></span></div></li>
</ul>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

Answer №1

It was not functioning correctly due to the presence of two classes:

nightText nightTextNight

To address this issue, you should verify:

if(nightText.className === "nightText nightTextNight")

var nightBtn = document.getElementById("switch");
var body = document.getElementById("body");
var header = document.getElementById("header");
var navbar = document.getElementById("navbar");
var nightText = document.getElementById("nightText");

function nightMode() {
nightBtn.classList.toggle("switchNight");
body.classList.toggle("night");
navbar.classList.toggle("navbarNight");
nightText.classList.toggle("nightTextNight");
if(nightText.className === "nightText nightTextNight") {
nightText.innerHTML = "<i class='fa fa-sun-o' aria-hidden='true'></i>";
} else {
nightText.innerHTML = "<i class='fa fa-moon-o' aria-hidden='true'></i>";
};
  console.log(nightText.className);
}
body {
background-color: white;
transition: background-color ease 0.3s;
padding: 0;
margin: 0;
font-family: sans-serif;
}

.night {
background-color: #3f4b5e;
transition: background-color ease 1s;
}

.switch {
height: 35px;
width: 35px;
border-radius: 50%;
background-color: #092d30;
border: 3px solid wheat;
float: right;
z-index: 4;
transition: background-color ease 1s;
margin-top: 12px;
margin-right: 4px;
cursor: pointer;
text-align: center;
line-height: 17.5px;
position: relative;
}

.switchNight {
background-color: wheat;
border: 3px solid #092d30;
z-index: 4;
transition: background-color ease 1s;
}

.textNight {
color: white;
}

.switch:hover {
background-color: #4d5e77;
transition: background-color ease 1s;
}

.switchNight:hover {
background-color: #fff2d8;
transition: background-color ease 1s;
}

/* --------------------- NAV BAR ------------------ */

.navbar {
width: 100%;
height: auto;
background: #f4f7f9;
position: fixed;
margin-top: 0;
padding: 0;
border-bottom: 3px solid #2fb3f9;
}

.navbar li {
list-style-type: none;
display: inline;
height: auto;
}

.navbar li a {
padding: 20px 25px;
text-decoration: none;
display: inline-block;
font-size: 20px;
font-weight: bolder;
color: #516f7f;
}

.navbar li a:hover {
color: #ff9d00;
transition: color ease 0.3s;
}

.navbarNight {
background-color: #556bb5;
border-bottom: 3px solid white;
}

.navbarNight li a {
color: white;
}

.nightText {
position: absolute;
color: white;
font-weight: bolder;
top: 9px;
right: 12px;
}

.nightTextNight {
color: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<title>Night Mode - TEST</title>
</head>
<body id="body">
<div id="container">
<div id="nav">
<ul id="navbar" class="navbar">
<li><a href="#">Home</a></li>
<li><a href="#">About me</a></li>
<li><div id="switch" class="switch" onclick="nightMode()"><span id="nightText" class="nightText"><i class="fa fa-moon-o" aria-hidden="true"></i></span></div></li>
</ul>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

Note: I included

console.log(nightText.className);
for displaying the classes; feel free to remove it.

Answer №2

To easily switch between day and night mode, simply toggle the icon class instead of altering the entire i tag.

var sunBtn = document.getElementById("toggle");
var sunBtnIcon = document.getElementById("toggle-icon");
var body = document.getElementById("body");
var header = document.getElementById("header");
var navigation = document.getElementById("navigation");

function toggleMode() {
    sunBtn.classList.toggle("toggleSun");
    body.classList.toggle("day");
    navigation.classList.toggle("navigationNight");
    sunBtnIcon.classList.toggle("fa-sun-o");
    sunBtnIcon.classList.toggle("fa-moon-o");
}

HTML:

<ul id="navigation" class="navigation">
                <li><a href="#">Home</a></li>
                <li><a href="#">About me</a></li>
                <li><div id="toggle" class="toggle" onclick="toggleMode()"><i class="icon fa fa-moon-o" aria-hidden="true" id=“toggle-icon”></i></span></div></li>
            </ul>

Answer №3

One suggestion could be to group all elements that might have a unique style for nighttime in a div or even the body, and then simply apply a "night" class to that wrapper.

This way, you can customize the styles of your elements with ease:


.night .navbar {
  ... night-specific style adjustments ...
}

With this approach, toggling between day and night modes would involve adding or removing the class from the wrapping element. Any new classes added would only affect specific properties that needed changing on those elements.

Answer №4

To effectively disregard the id, utilize an Attribute and use a loop, such as data-mode. See the example below:

var modes={
day:{
      switch:"switch", body:"day", navbar:"navbar",icon:"fa fa-moon-o"
},
night:{
      switch:"switchNight switch", body:"night day", navbar:"navbarNight navbar",icon:"fa fa-sun-o"
   }
}
function changeMode(arg){
window.mode=arg;
var elem=document.querySelectorAll('[data-mode]');
for (var i=0; i<elem.length; i++){
var key=elem[i].getAttribute("data-mode");
elem[i].classList=modes[arg][key];
}

}
window.mode="day";
body {
background-color: white;
transition: background-color ease 0.3s;
padding: 0;
margin: 0;
font-family: sans-serif;
}

.night {
background-color: #3f4b5e;
transition: background-color ease 1s;
}

.switch {
height: 35px;
width: 35px;
border-radius: 50%;
background-color: #092d30;
border: 3px solid wheat;
float: right;
z-index: 4;
transition: background-color ease 1s;
margin-top: 12px;
margin-right: 4px;
cursor: pointer;
text-align: center;
line-height: 17.5px;
position: relative;
}

.switchNight {
background-color: wheat;
border: 3px solid #092d30;
z-index: 4;
transition: background-color ease 1s;
}

.textNight {
color: white;
}

.switch:hover {
background-color: #4d5e77;
transition: background-color ease 1s;
}

.switchNight:hover {
background-color: #fff2d8;
transition: background-color ease 1s;
}

/* --------------------- NAV BAR ------------------ */

.navbar {
width: 100%;
height: auto;
background: #f4f7f9;
position: fixed;
margin-top: 0;
padding: 0;
border-bottom: 3px solid #2fb3f9;
}

.navbar li {
list-style-type: none;
display: inline;
height: auto;
}

.navbar li a {
padding: 20px 25px;
text-decoration: none;
display: inline-block;
font-size: 20px;
font-weight: bolder;
color: #516f7f;
}

.navbar li a:hover {
color: #ff9d00;
transition: color ease 0.3s;
}

.navbarNight {
background-color: #556bb5;
border-bottom: 3px solid white;
}

.navbarNight li a {
color: white;
}

.nightText {
position: absolute;
color: white;
font-weight: bolder;
top: 9px;
right: 12px;
}

.nightTextNight {
color: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>;
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<title>Night Mode - TEST</title>
</head>
<body data-mode="body">
<div>
<div>
<ul class="navbar" data-mode="navbar">
<li><a href="#">Home</a></li>
<li><a href="#">About me</a></li>
<li><div class="switch" data-mode="switch" onclick="changeMode(mode=='night'?'day':'night');">
<span class="nightText">
<i class="fa fa-moon-o" data-mode="icon"></i>
</span>
</div>
</li>
</ul>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

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

@media doesn't seem to be functioning properly when the screen width is below

I've been working on making my website fully responsive, but I've run into an issue where it won't recognize anything below 980px in width. Here is the CSS code I'm using: @media screen and (max-width:1029px){ h1{ font-size ...

Building CSS columns

Similar Inquiry: Creating dual columns in HTML/CSS layout I'm exploring ways to achieve a two-column layout within a wrapping div element. Currently, I have the following CSS code snippet which centers a div inside the browser: .wrapper {width: ...

Arrange a row of fifteen child DIVs in the form of bullets at the bottom of their parent DIV

Currently, I am working on customizing a slider by adding bullets. My goal is to create a gradient background for the parent div containing these bullets. However, when I try to increase the height of the parent div, all the bullets align themselves at the ...

An issue arises when attempting to fetch data using next.js: a TypeError occurs indicating that

I'm currently working on setting up a next.js website integrated with strapi, but I've encountered an issue with my fetch request. Oddly enough, when I test the request using Postman, the data is successfully returned, indicating that the endpoin ...

Tips for broadcasting the blob

I am currently working on a radio system project that involves streaming live audio from a microphone to the user in real-time. However, I am new to using node.js and unsure of how to achieve this. Can anyone provide guidance on how to stream the audio fro ...

"An error message stating 'Express: The body is not defined when

I'm encountering an issue while trying to extract data from a post request using express. Despite creating the request in Postman, the req.body appears empty (console.log displays 'req {}'). I have attempted various solutions and consulted s ...

Is it possible to access the service and 'self' directly from the HTML template?

When working with Angular 6, one method to access component properties from a service is to pass 'self' to the service directly from the component. An example of this implementation is shown below: myComponent.ts public myButton; constructor(p ...

Modifying the value property of the parent element

Here is an example of the HTML code I am working with: <td value='3' style='text-align: center'> <select class='selection' onchange=''> <option value='1'>1</option> <opti ...

The initial menu option stands out due to its unique appearance, created using the :first-child

I am currently designing a website menu and I would like the .current-menu-item - current item, to have a different appearance. However, I want the first item in this menu to have rounded corners (top left, bottom left). How can I achieve this using the :f ...

Creating a step wizard form with ReactJs can be accomplished by breaking down the form into

I have developed a resume generation application with two main components: BasicDetails and EmploymentDetails. To see a working example, click here: https://codesandbox.io/s/next-dynamic-testing-issue-forked-h1nt8 index.js file: <form onSubmit={ha ...

Why does my jQuery code target all the text values?

Looking to grab a specific table cell number and multiply it by an input value on focusout, but having trouble with the selector grabbing all cells with "front" in the name. Check out the code below: jquery $(document).ready(function(){ $(".percent") ...

Can you provide the date time format used in the JSTL fmt tag?

To display date and time in JSTL, the fmt tag can be utilized. Details can be found here In order to format the date for use with front end tools like the datatable, a specific date format needs to be specified. By using parameters such as type or dateSty ...

Changing the alignment of divs to center instead of the right side

I am currently working on a project that involves creating a tiled interface with responsive tiles. One issue I have encountered is that all the tiles are shifting to the left side of the div and not getting centered, no matter what I try. To see the pro ...

Building an HTML form to generate an array of objects by collecting form data

Hey there, I'm working on an HTML form in React that utilizes form action and FormData. However, when I extract the formData using my method, it shows a structure like this: https://i.stack.imgur.com/nzgLX.png My goal is to have an array of objects ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

Obtaining data from console.log and showcasing it within a div element

Currently, I am facing a challenge where I want to retrieve the title, plot, and poster using the themoviedb API. However, I am lost on how to begin coding this. Whenever I perform a search, the information is displayed in the console log of the browser. ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

Tips for managing erroneous data in csv files using Node.js

I am currently working on an application that parses csv files using the csv module. It is functioning well, but I am facing a problem where if there is a bad row in the csv file, the entire process fails. Is there a way to skip bad rows and continue stre ...

Is it possible to rearrange column order in Bootstrap 4x according to different viewport sizes?

One of the great things about Bootstrap is its ability to rearrange columns regardless of the HTML structure. However, I am looking to have a different order of elements when the viewport size is smaller (e.g., Mobile). The current HTML structure looks li ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...