Tips for implementing a JavaScript 'getElementById' on an HTML CSS toggle button

I am in need of assistance to activate my HTML/CSS 'Toggle Switch' using JavaScript.

My goal is to have the text within the DIV hidden by default, and when the slider (switcher) is swiped to the left, it should trigger the DIV to be shown using JavaScript.

I believe I am on the right track, but there seems to be a small issue with my current action...

function toggleDiv() {
  var triggeredDiv = document.querySelector('.triggeredDiv');
  if (document.getElementById('flipswitch').checked) {
    triggeredDiv.classList.remove('shown');
  } else {
    triggeredDiv.classList.add('shown');
  }
}

document.getElementById('flipswitch').addEventListener("change", toggleDiv);
.flipswitch {
  position: relative;
  width: 200px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.flipswitch input[type=checkbox] {
  display: none;
}

.flipswitch-label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid #999999;
  border-radius: 50px;
}

.flipswitch-inner {
  width: 200%;
  margin-left: -100%;
  -webkit-transition: margin 0.3s ease-in 0s;
  -moz-transition: margin 0.3s ease-in 0s;
  -ms-transition: margin 0.3s ease-in 0s;
  -o-transition: margin 0.3s ease-in 0s;
  transition: margin 0.3s ease-in 0s;
}

All other CSS code goes here
All Other HTML Code Goes Here

Answer №1

The issue at hand is that you're attempting to target the flipswitch by an id of flipswitch when in reality you assigned the switch an id of fs. To rectify this, simply update the references in the javascript code to be:

document.getElementById('fs')

in place of

document.getElementById('flipswitch')

Answer №2

Instead of utilizing document.getElementById, it is recommended to use a method that retrieves elements by class, as per the definition in your markup.

Furthermore, the input checkbox does not toggle the checked attribute; instead, it toggles the state of the triggered div.

We can adjust the code to make it function properly:

function toggleDiv() {
   this.element || ( this.element = document.querySelector('.triggeredDiv') );

   this.element.classList.toggle("shown");
  }

Code with explanatory comments:

function toggleDiv() {
  /*
   If there is no reference in `toggleDiv.element`, 
   we employ `document.querySelector` to acquire
   and store the reference to the element with the class `.triggeredDiv`
   This ensures a single DOM traversal to retrieve the element,
   regardless of how often the function is called,
   which enhances performance.
  */
  this.element || (this.element = document.querySelector('.triggeredDiv'));

  /*
   Once we have the element, we simply toggle the `shown` class
   using the `classList.toggle` method.
  */
   this.element.classList.toggle("shown");
}

  document.querySelector('.flipswitch').addEventListener("change", toggleDiv);

function toggleDiv() {
   this.element || ( this.element = document.querySelector('.triggeredDiv') );
   
   this.element.classList.toggle("shown");
  }
  
  document.querySelector('.flipswitch').addEventListener("change", toggleDiv);
.flipswitch {
  position: relative;
  width: 200px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.flipswitch input[type=checkbox] {
  display: none;
}

/* CSS properties for flipswitch are defined here */

.triggeredDiv {
  display: none;
}

.triggeredDiv.shown {
  display: block;
}
<div class="flipswitch">
  <input type="checkbox" name="flipswitch" class="flipswitch-cb" id="fs">
  <label class="flipswitch-label" for="fs">
    <div class="flipswitch-inner"></div>
    <div class="flipswitch-switch"></div>
  </label>
</div>

<div class="triggeredDiv">
  Show Text
</div>

Answer №3

In order for your code to function correctly, I would recommend replacing the two occurrences of

document.getElementById('flipswitch')
with document.getElementById('fs') within your function.

Illustrative JSFiddle Model: https://jsfiddle.net/xu4t9zf7/

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

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

Having trouble with jQuery AJAX verifying the existence of an email in the database?

I'm experimenting with jQuery, AJAX, PHP, and MySQL to validate if an email entered in a form exists in a database. Here's the current jQuery code I am using: $.post('check-email.php', {'suEmail' : $suEmail}, function(data) { ...

Returning JSON objects from ASP.NET WebMethod without using the response method

My webmethod is quite simple: <WebMethod(Description:="Does something.")> _ <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _ Public Shared Function ReturnJSONData() As Person Dim guy As New Person guy.Name = "Joe" guy.Age = 8 ...

Pop-up confirmation dialog in JQuery following an AJAX request

In order to validate on the server side whether a person with a specific registration number already exists in the database, I have implemented a process. If the person is found registered, the program flow continues as usual. However, if the number is not ...

How can I dive into a nested array to access the properties of an object within?

My array, called sportPromise, is structured like this: 0: Array[0] 1: Array[1] 2: Array[2] 3: Array[3] When I run console.log(angular.toJson($scope.sportPromise, 'pretty'));, the output looks like this: [ [], [ { "id": 5932, ...

Having issues with Merge Sort functionality in React not functioning as anticipated

I've spent hours trying to debug this code, but I can't seem to figure out what's wrong. The 'items' variable consists of a list of div elements with randomly generated heights. Can someone please assist me in identifying the issue ...

Activate child component function using react-navigation before removal

Currently, I am utilizing React Navigation for a react native application in conjunction with Expo-Video-Player. My goal is to monitor the duration for which a video has been played once the screen is dismissed and then log this information in the console. ...

Comparing parameters between two functions in Javascript: a step-by-step guide

I am currently working on solving this problem: var name; var totalScore; var gamesPlayed; var player; var score; // Creating the game player object function makeGamePlayer(name, totalScore, ga ...

What are the steps to refresh the content in a glightbox slider?

I'm currently utilizing Glightbox to set up a gallery that includes descriptions for images. I have a specific request where I want the button text to update on click. However, when the button is clicked and the lightbox reopens, the text on the butto ...

Include a new item into the existing one and iterate through the information within it

Is there a way to iterate through the compositions array within the sample object and then use that data to fill the compositions array of the objToAdd object? const sample = { lin: { "clo": [ { "mode": 19, "id": ...

Is there a way to extract information from an external XML document and incorporate it into an HTML file?

I am attempting to extract information from an XML file that is not stored on my website's server. My goal is to utilize this data for various purposes, such as generating charts. One specific example involves using weather data from an XML file locat ...

The AJAX functionality for POST, PUT, and DELETE requests is functioning properly, however, the GET request is experiencing CORS

I've been delving into Java, Spring, PHPmyadmin, and a combination of pure HTML and JS for my first API project. I've managed to successfully implement POST, PUT, and DELETE requests, but I'm encountering an issue with GET requests by ID usi ...

Mastering Angular, Typescript, and Firestore: Unlocking the Secrets of Returning an Observable Value in an If Statement

I am currently utilizing Angular along with Firestore. I have encountered an issue where, upon page refresh, the value returned from Firestore appears as undefined within my route guard. Interestingly, hardcoding a return value of true or false seems to wo ...

Getting the list items separated from the unordered list in Selenium

My current task involves navigating a list and selecting the correct text entry. The list contains only 2 items: <ul> <li><span>first</span></li> <li><span>second</span></li> </ul> However, ...

Exploring the ENV variable settings while developing in a Node.js environment

I have created a configuration file for handling environment variables and I need to test it in the development environment. In the development cycle, I want to test both production and development variables to receive different configured values. How can ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Having trouble initiating tablesorter within an iframe

When attempting to delete a row from tablesorter within an iframe, I am able to successfully remove the row. However, I am encountering issues when trying to trigger the update tablesorter. Below is my current approach: $(document).ready(function () { ...

Modifying the date formatting in JavaScript if it is incorrect

Recently, I developed a mobile application that can scan QR-CODEs containing various information, including a date. However, there have been changes in the format of the date within the QR-CODE between previous and new versions. Previously, the date was fo ...

Insert a new, unique div onto an HTML webpage using JavaScript, ensuring no duplicates are created

Having an issue with this code snippet where nothing is being added. It seems like the variable result may not be taking a number or something else, but I'm not entirely sure why. $(document).ready(function () //document.getElementById(1).style. ...

Encountering issues with jQuery AJAX POST request

I'm currently facing an issue while attempting to send a post request to parse JSON formatted data into my webpage. Here's an example of the query: $("#click").click(function () { $.ajax({ type: "POST", url: "http://ut-pc-236 ...