Having trouble getting the if statement to work for a basic JavaScript toggle feature

The functionality implemented in the resize() function involves checking for the presence of the switch class on the body element. If the class is present, it is removed upon firing the resize function; otherwise, the class is added.

However, a problem arises with the snippet below when the button is clicked – it fails to act as a toggle. Instead, it only registers one click and does not restore to its original state.

Why is this basic JavaScript code not functioning correctly, and what are some approaches to resolve this issue?

function resize() {
  var body = document.querySelector( 'body' );
  
  if( body.classList.contains( 'switch' ) ){
    body.classList.remove( 'shrink' ); 
  }
  else {
    body.classList.add( 'shrink' ); 
  }
}

var switcher = document.getElementById( 'switch' );
switcher.addEventListener( 'click', resize );
p {
  text-align: center;
  margin-bottom: 1rem;
  transition-property: color;
  transition-duration: 1.5s;
}
.bar {
  width: 22.5rem;
  height: 10rem;
  background-color: #555;
  border-radius: 5rem;
  position: relative;
  transition-property: background-color;
  transition-duration: 1.5s;
}
.knob {
  width: 12rem;
  height: 12rem;
  background-color: #000;
  border-radius: 10rem;
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY( -50% );
  transition-property: right, background-color;
  transition-duration: 1s, 1.5s;
}
:checked ~ label p { color: #888 }
:checked ~ label .bar { background-color: #888 }
:checked ~ label .knob {
  background-color: #777;
  right: 10.5rem
}
.shrink { transform: scale( 0.8 ) }
<head>
  <style>
    * { margin: 0 }
    html { font-size: 10px }
    html,
    body,
    main { height: 100% }
    body {
      transition-property: transform;
      transition-duration: 1s;
    }
    main {
      font-family: arial;
      font-size: 6rem;
      display: flex;
      text-transform: capitalize;
    }
    input { display: none }
    label,
    p {
      user-select: none;
      cursor: pointer;
      margin: auto;
    }
  </style>
</head>
<body>
  <main>
    <input type="checkbox" id="checkbox">
    <label for="checkbox" id="switch">
      <p>switch</p>
      <div class="bar">
        <div class="knob"></div>
      </div>
    </label>
  </main>
</body>

Answer №1

Ensure you're verifying the existence of the switch class, but aiming to toggle the shrink class instead. It's important to remove the 'switch' class so that contains('switch') can return false when necessary.

Answer №2

The resize() function includes a check to see if the body element has the switch class. If it does, the switch class is removed when the resize event is triggered.

However, instead of removing the switch class, you are actually adding and removing the 'shrink' class.

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

The Redis ReJSON consistently throws two errors at me: one for a missing key in a non-terminal path, and another for the requirement to create a

Understanding the second error is relatively simple, while the first error poses a bit more of a challenge. I have experimented with various combinations to address this error, but unfortunately, no progress has been made. When I check my console, I recei ...

Angular encountered an issue while attempting to differentiate '[object Object]'. The permissible types for differentiation are limited to arrays and iterables

I need help iterating through an Object received from a service call and displaying it in a table using *ngFor. Unfortunately, I encounter the following error during this process: Error trying to diff '[object Object]'. Only arrays and iterables ...

What is the method to retrieve the index or row number using the map function in Google Sheets?

Currently, I am attempting to retrieve the row number where the row meets certain criteria. However, I seem to be encountering an issue: Instead of getting the desired result, I am obtaining an array like this: [,,2] Although I have attempted using filter ...

The Document.querySelector() method is not displaying every element

As a beginner, I am currently exploring the world of relative CSS selectors and JSPath for my automation scripts. During my journey, I noticed that there are differences in the return statements between these two methods. Below is an example demonstrating ...

Is there a way to transform authorid into postid in order to retrieve author information and store it in my authorDocument array?

**Can you help me troubleshoot why this code is not functioning properly? ** let posts = await postsCollection.aggregate([ {$match: {_id: new ObjectID(id)}}, {$addFields: {authorId: { $toObjectId: "$author"}}}, {$lookup: {from: "user ...

Using JavaScript to create an array within an object and adding new elements to the array

I'm just beginning to learn programming and experimenting with React. I have a function called addComment that is triggered when a user adds a comment to a news article. At this point, I need to create a property called comments (an array) and either ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...

What is the best method to set variables to zero using this array in JavaScript?

I am looking to extract strings from an array and set them all to zero. The original array consists of: var myArray = ["apple", "banana", "cherry", "date"]; The expected outcome should be: var apple = 0; var banana = 0; var cherry = 0; var date = 0; I ...

Utilize Mongoose to seamlessly integrate online shopping cart items into MongoDB

I am facing an issue while trying to insert a shopping cart of items in the form of a JSON object into a MongoDB collection using a mongoose schema. Although the customer's ID is successfully stored (extracted from the User DB), unfortunately, the ca ...

Tips for eliminating the page margin in Java when converting HTML using iTextPdf with HTMLConverter

No matter how hard I've tried, setting the body with padding: 0 and margin: 0, as well as attempting to set the doc() with setMargin, nothing seems to be effective ...

I recently edited my htaccess file to redirect my webpage, but now I'm facing issues with my CSS, images, and

Here is the htaccess code I am using: RewriteRule ^example1/([A-Za-z-]+)/?$ example2.php?name=$1 [NC] The page is loading, but the CSS and JS are not rendering correctly. Can anyone assist me in resolving this issue? ...

Failed to access the 'totalQty' property as it is undefined

I have developed a cart object that can hold products in a shopping cart. The issue arises when an item is undefined before it gets added to the cart. How can I ensure that the cart is defined even when it's empty during the session? I am using ejs. ...

Having trouble with Jquery slide toggle and append functionality?

I'm struggling to get this code right. Could it be a syntax issue? jQuery is confusing me, as the alert works but not the functions. Is there something specific I need to do in order to make them work properly? How can I ensure that everything runs sm ...

Tips for storing a single document in two separate collections within the same MongoDB database

I am currently exploring nestjs and I am faced with a challenge. My goal is to retrieve a document from collection_1 and then store the same document into collection_2. I have tried using the $out aggregation, but found that I am only able to save one docu ...

What exactly is the significance of the error message "The JSX element type 'Header' does not have any construct or call signatures"?

I am encountering an error in my code, specifically with the Header and List elements. The error message keeps stating that the JSX element type Header does not have any construct... What could be causing this issue? import React, { useEffect, useState } ...

Error in Angular: Unexpected '<' token

After setting up my angular and express app using the angular-cli and express command lines, I successfully built the angular app with the ng build command. However, when attempting to serve it with the express server, I encountered the following error in ...

How can you merge one object with two different mongoose models?

Consider the scenario where I have two mongoose models set up: User Model Business Favorite Model Currently, I'm successfully retrieving the combined result if a user has any favorite businesses. However, I suspect that my current implementation mi ...

Unable to designate the drop-down option as the default selection

Can anyone help me with setting a default drop-down value using JavaScript? I have been struggling to achieve this. You can find my code on jsFiddle <div ng-controller="csrClrt"> <div ng:repeat="(key, item) in items track by $index"> ...

Tips for making nested sliding divs within a parent sliding div

Is it possible to slide a float type div inside another div like this example, but with a white box containing "apple" text sliding inside the black div it's in? I have attempted to recreate the effect using this example. Here is my current JavaScript ...

Having trouble with loading a new page on an HTML website

My website is successfully updating the database, printing all values, but for some reason the new page is not opening. The current page just keeps refreshing and I'm receiving a status of 0. Below is my code snippet: try{ console.log("here1 "+e ...