Opting for a CSS toggle on a div as opposed to an input field

I was on the hunt for a way to create a toggle button and stumbled upon one that fit my needs perfectly. However, the example I found uses the toggle on an input field whereas I want to implement it on a div element. Despite attempting various modifications to the CSS classes, I'm unable to get it to function properly.

Here is the CSS code snippet I am currently using:

.toggle {
  position: relative;
  display: inline-block;
  width: 90px;
  height: 34px;
}

.toggle input {display:none;}

.switch {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ca2222;
  -webkit-transition: .4s;
  transition: .4s;
  border-radius: 34px;
}

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

input:checked + .switch {
  background-color: #2ab934;
}

input:focus + .switch {
  box-shadow: 0 0 1px #2196F3;
}

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

/* Additional CSS */
.switch::after {
  content:'OFF';
  color: white;
  display: block;
  position: absolute;
  transform: translate(-50%,-50%);
  top: 50%;
  left: 50%;
  font-size: 10px;
  font-family: Verdana, sans-serif;
}

input:checked + .switch::after {  
  content:'ON';
}
/* End of Additional CSS */

This is how the HTML in the example looks like:

<label class="toggle"><input type="checkbox" id="togBtn"><div class="switch round"></div></label>

Currently, when I apply this structure everything behaves as expected. However, the structure of my own HTML and the div I intend to toggle appears as follows:

<div class="facetwp-facet facetwp-facet-special facetwp-type-checkboxes" data-name="special" data-type="checkboxes">
    <div class="facetwp-checkbox" data-value="yes">Yes</div>
</div>

I've made adjustments to the CSS from the example to suit the div I want to toggle but seem to be facing obstacles in getting it to work correctly.

Perhaps the solution is straightforward, but I find myself stuck. Any assistance would be greatly appreciated!

Answer №1

Instead of applying the :checked class to the input checkbox, I added it to the slider div.

This required some modifications in the CSS code.

.slider.checked{...} was used instead of input:checked + .slider {...}

.slider:focus{...} replaced input:focus + .slider {...}

.slider.checked:before {...} substituted

input:checked + .slider:before {...}

Check out the Demonstration using Jquery

  • Incorporating Jquery to toggle the checked class on the slider div when clicked.

$(".slider").click(function(){
  $(this).toggleClass("checked");
});
.switch {
  position: relative;
  display: inline-block;
  width: 90px;
  height: 34px;
}


.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ca2222;
  -webkit-transition: .4s;
  transition: .4s;
   border-radius: 34px;
}

/* More CSS styles here */

.slider.checked:after
{  
  content:'ON';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="switch">
    <div class="slider round"></div>
</div>

Try the Demo with Javascript

  • Utilizing Javascript to toggle the checked class on the slider div upon click.

function sliding(obj){
 obj.classList.toggle("checked");
}
.switch {
  /* CSS styles here */
}

.slider {
  /* More CSS styles here */
}

/* Remaining CSS styles */
<div class="switch">
    <div onclick="sliding(this);" class="slider round"></div>
</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

What is the best way to extract the name from JSON data?

I have a list of items in my HTML with data attributes. When a user clicks on one of the items, I want to display or append a list of related suburbs for that selected item in another list. This is being achieved using ajax. <ul id="cities"> <l ...

Fluid Cursor Movement in the Atom Text Editor

I encountered an issue where adding a smooth caret animation in the atom editor caused the background to start blinking uncontrollably. Below is the code snippet I used to add the animation in my style.less file: atom-text-editor .cursor { transition: ...

Vertical and floating alignment

Can you help me with this HTML/CSS challenge? User: Support: Emily Johnson Alex Roberts I am looking to have two input boxes aligned vertically on both the left and right ...

Embed Google Maps inside a Twitter-Bootstrap container

I am currently working on integrating Google Maps into my web server. Since I am not proficient in Front-End development, I am facing challenges with bootstrap elements. However, I have managed to code the necessary components for Google Maps to function p ...

Bootswatch's Bootstrap 4 dropdown and margin error issue

Recently, I decided to experiment with the new version of Bootswatch that is based on Bootstrap 4. However, I encountered a couple of issues - the "Cards" seem to have no margin and the dropdown in the menu doesn't function as expected. Can anyone she ...

Interactive pop-up text box for data cells in a table

I have implemented a textarea in the td cell of each row within column 3 to store description specific to that row. The goal is for the current description in the td's textarea to be copied over to the textarea located inside #div_toggle when the user ...

Steps for clearing a set of checkboxes when a different checkbox is selected

While working on a website I'm developing, I encountered an issue with the search function I created. The search function includes a list of categories that users can select or deselect to filter items. This feature is very similar to how Coursera has ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

Encountered a problem while executing CSS in Shiny R

I am attempting to incorporate my css file into Shiny R. I have been able to run the application without any issues before adding the style.css file. Below are the steps I have taken: library(shiny) library(tidyverse) library(leaflet) library(leaflet.extra ...

What is the difference between finding the XPath of immediate child text and all descendant text?

Looking to extract the top-level category from this structure: <ul class="categories"> <li>My top level category <ul> <li>my second level category</li> </ul> </li> </ul> ...

CSS padding not behaving as expected

Hey there, I have a question regarding adjusting text inside a div using padding. I tried applying the padding command, but it doesn't seem to have any effect. You can find the relevant part of my code here <html> <head> <meta ch ...

Step-by-step guide to implementing a floating action button on the bottom-right corner of a screen using Material-UI in a React application

I have been attempting to place the FloatingActionButton on the bottom right corner of the screen. To achieve this, I am utilizing the following library: http://www.material-ui.com/#/components/floating-action-button import React, { Component } from "reac ...

When using jQuery, the content loaded with the $ajax function only displays after refreshing the page

Located on an external server is a directory containing various .html files, including one named index.html. The server has the ability to load either the folder name or foldername/index.html in its URL. Each html file within the directory loads a corresp ...

Repurposing components like custom text inputs, spans, and more in ASP.NET MVC using Razor

Our team is currently working on a website project where we keep re-using components repeatedly. One particular instance involves a span that functions as a warning light. It's accompanied by some C# code with properties for color and text, Javascript ...

What is the method to create a link that doesn't take up the entire page?

As a beginner in HTML, I have been working on a website for fun and facing an issue with buttons. When I add a button, the entire area becomes clickable, even if there is empty space around it. This means that you can click on the left or right side of the ...

Activate validation checks when the Div is loaded

I have a situation where I have multiple divs on my page, with only one visible at a time due to the use of an update panel. Within the third div, I need to implement validations using jQuery. <script src="http://ajax.aspnetcdn.com/ajax/jquery.valida ...

What is the method for determining the width of a Mat-Table once it has been displayed?

When utilizing Angular Material Mat-Table in conjunction with Angular 8, I am passing the dataSource dynamically. The number of rows and columns varies each time. Is there a method to calculate the width of the table once it is rendered on the screen? &l ...

What is the most efficient way to implement hiding/showing elements, adding/removing classes, and optimizing code in jQuery?

Looking for a more elegant solution to toggle classes on a div when clicking a button? Current code logic: jQuery(document).ready(function($) { // Removing/adding classes to show/hide div elements on button click // More efficient w ...

Can the Apache tomcat located at "localhost:8080/app.html" be accessed from a different network?

Currently, I am hosting my webpage on a Tomcat server. While I can easily access it from different computers on the same network, I am curious if there is any way to access this webpage/localhost from a different network? ...

Is there a way to include a button within the Rails code that would allow users to add a present using the <%= link_to_add_fields "Add A Gift", f, :presents %> function

I'm having trouble figuring out how to insert a button into a link_to_add_fields, like this: <%= link_to_add_fields "Add Another Item", f, :items %> while working on my Rails App. I've attempted to include class: "btn btn-mini btn-info" ...