A guide to updating content using a toggle button in HTML, CSS, and JavaScript

Currently, I am facing a challenge with toggle switches while working on my website.

I have successfully created the toggle button, but now I want to implement a function that allows me to switch between two different contents.

The task seems simple - when toggled to the right, I want to display the text "Hey" within a div, and when toggled to the left, I want to display the text "Bye". However, I am struggling to make this work. What steps should I take?

How can I achieve this desired functionality?

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #E21C90;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
  background-color: #E21C90;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<label class="switch">
  <input type="checkbox" checked>
  <span class="slider round"></span>
</label>

Answer №1

If you want to achieve the desired effect, you can attach an event listener to the checkbox input and then change the display property of the parent elements of the sliders based on the checkbox state. It's worth noting that in this illustration, I have utilized div elements as the parent containers, but any block-level element would serve the purpose.

let mainContent = document.querySelector('#main_content');
let secondaryContent = document.querySelector('#secondary_content');

document.querySelector('.switch input').addEventListener('change', e => { 
  mainContent.style.display = e.target.checked ? 'block' : 'none';
  secondaryContent.style.display = e.target.checked ? 'none' : 'block';
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #E21C90;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
  background-color: #E21C90;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

#secondary_content {
  display: none;
}
<label class="switch">
  <input type="checkbox" checked>
  <span class="slider round"></span>
</label>

<div id="main_content">Slider 1</div>
<div id="secondary_content">Slider 2</div>

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

Is it possible to utilize a single template and dynamically fill it with content as needed?

Is there a method to utilize a single template and dynamically insert content into it? http://jsfiddle.net/cmckeachie/mtV62/light/ var routingExample = angular.module('FunnyAnt.Examples.Routing', []); routingExample.controller('HomeControl ...

Retrieve the website address from a string of HTML code

I'm struggling to extract the URL from a given String that contains an HTTP response with an HREF tag. I've managed to identify the start of the links, but I need to stop the string as soon as the HREF tag ends. How can I accomplish this? public ...

Loop through each of the div elements inside another div

Is there a way to loop through the nested divs within a parent div and display a message if they all have the same 'display' value of 'none'? I'm new to learning jQuery and really need to understand it fully. <div class="te ...

Utilizing React Typescript to Efficiently Manage Multiple Checkboxes within a List

I'm working on a scenario where I have to manage multiple checkboxes in a list Only one checkbox can be selected at a time For example, if I toggle on Checkbox 1 and then click on Checkbox 2 - I want to automatically toggle off Checkbox 1 as I toggl ...

Sending an array of JSON data from PHP to JavaScript

After exploring various solutions on how to get JSON in JavaScript from a PHP array, I am still encountering an error. My myfile.php file includes: <?php ................ print json_encode($data, JSON_NUMERIC_CHECK); mysql_close($con); ?> <html&g ...

PHP code that generates a drop-down list using a foreach iteration

all I'm encountering a slight issue with trying to create a dynamic drop down list. Here's the code I've written: <select name='categoryID' > <?php foreach( $categories as $category)?> <option value="<?p ...

What techniques can be used to ensure that an ASMX web service sends JSON data to the client in response to an HTTP GET

Trying to integrate the official jQuery autocomplete plugin with an ASMX web service in an ASP.NET 3.5 Web Forms application has been challenging. The autocomplete plugin requires HTTP GET calls with specific query string parameters, but I'm strugglin ...

Prevent users from changing dropdown options after a form submission fails using Javascript and Jquery

Currently, I am pursuing the tech degree at Team Treehouse and my third project involves creating an interactive form. To simplify my issue, I will outline it in bullet points: The credit card payment method should be preselected when the page loads. I n ...

Tips for updating content within two separate tabs using jQuery

By default, the home tab is displaying blank as per the code below. Content will only appear when the product ordering tab is clicked. I initially implemented this logic in JavaScript, but encountered issues when trying to replicate it in jQuery. Can anyon ...

Transferring callback variables from an Express GET request to a forked process in Node.js

I encountered an issue while trying to transfer the callback variables from app.get() to a forked process. The error message I received was: TypeError: Converting circular structure to JSON The primary goal behind this endeavor is to enable a main node w ...

Generating a dynamic method for uploading multiple files

Is there a way to dynamically generate multiple upload forms upon clicking a button? I currently have code that allows for uploading one file, but I would like to be able to add additional forms for each file. In other words, if I need to upload 7 files, I ...

React Router issue with page navigation not working properly

Currently, I am utilizing the most recent version of React-Router (v6) for my one-page portfolio website. I have been using createBrowserRouter in conjunction with createRoutesFromElements to set up the routing and linking of pages. However, I've enco ...

Determining the spatial location of an object in Three.js in relation to the camera for the purpose of creating a trail

In my scene, I have an object (a pen) that rotates around its axis in the render loop using the following code: groupPen.rotation.y += speed; groupPen.rotation.x += speed; Additionally, I have a TrackballControls that allows the user to rotate the entire ...

``I encountered an issue with move_uploaded_file function not functioning properly within a

Every time I attempt to upload a file within the WordPress folder (wp-content/themes/twenty-twelve/uploads/), it fails when I submit the form. The path to my form is: wp-content/themes/twenty-twelve/template-parts/form.php <form id="Form" method=" ...

Locate a specific item within an array using TypeScript

Looking for a more efficient solution to retrieve data from a collection in Typescript. The data is structured as follows: myData: { Id: string, Name: string, Address: string Salary: number phone: number } We have approximately 500 records, eac ...

Looking to restrict the data retrieved from an API while utilizing ReactJS

I am currently fetching transaction data from an API. One of the fields in the response is buyer, which may sometimes be null. As a result, I am excluding any entries with a null buyer. This leads to varying numbers of results being displayed. My goal is t ...

JQuery Dialog concealing Bootstrap DateTimePicker

I am facing an issue with a bootstrap datetimepicker placed inside a JQuery dialog. The problem is that the datetimepicker gets hidden within the dialog, whereas I want it to be displayed on top of it Currently, this is how it appears: https://i.sstatic. ...

Is there a way to retrieve the ref value from another component file?

Below is the code found in App.vue: <script setup> import Nav from "./components/Nav.vue"; </script> <template> <Nav/> </template> ................................................................... Now, take a ...

Creating separate Vuex stores for dynamic components

This question really had me stumped for a while. I couldn't find the answer here (asking around didn't help either). However, after conducting some research and seeking advice from various sources, I believe I have finally arrived at a solution t ...

Page encountering NextJS cors error, while API route remains unaffected

In my Next.js application, I have encountered an issue where executing a call to fetch a page from an external website works perfectly fine when done from the backend through an API route. However, when attempting the same action from the frontend, I encou ...