Switch the toggle to activate or deactivate links

My attempt at coding a switch to disable and enable links using CSS is functional in terms of JavaScript, but the appearance is not changing. I am lacking experience in this area.

Here is my HTML Button code:

<label class="switch" isValue="0">
    <div class="slider round">
    </div>
</label>

Concerning the CSS:

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

input[type="checkbox"]:checked + input[type="hidden"] + .slider,
input[type="checkbox"]:checked + .slider {
    background-color: #2196F3;
}

input[type="checkbox"]:focus + input[type="hidden"] + .slider,
input[type="checkbox"]:focus + .slider {
   box-shadow: 0 0 1px #2196F3;
}

input[type="checkbox"]:checked + input[type="hidden"] + .slider:before,
input[type="checkbox"]:checked + .slider:before {
    transform: translateX(26px);
}

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

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

.dim.disabled {
    pointer-events: none;
    background-color: grey;
}

And for the JavaScript:

$(document).on('click', '.switch', function () {
    var v = $(".switch").attr("isValue");
    if (v == 1) {
        $(".switch").attr("isValue", "0");
        $(".dim").removeClass("disabled");
    }
    else {
        $(".switch").attr("isValue", "1");
        $(".dim").addClass("disabled");
    }
});

I suspect there is an issue with the use of checkboxes in this setup.

Your assistance on this matter would be greatly appreciated. Thank you.

Answer №1

Disregarding the unclear code suggestion, here is a breakdown of how a jQuery class toggle functions:

$(".toggle-button").on('click', function () {
  $(this)
    .toggleClass('inactive')
    .data('state', ($(this).hasClass("disabled")? 'off':'on'));
    
  console.clear();
  console.log('Current state: ', $(this).data('status') );
});
.switch > button {
  display: block;
  width: 68px;
  height: 68px;
  background-color: green;
  border-radius: 34px;
}

.switch.disabled > button {
  background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle-button" data-state="on"><button></button></div>

Answer №2

By utilizing only CSS, in case you prefer that approach. I thought it might be helpful since you mentioned that the JavaScript is functioning but the visual aspect is not changing.

Simple toggle

/** Example Body Styling **/

body {
  margin: 0;
  padding: 0;
  background: #f0f0f0;
}

* {
  box-sizing: border-box;
}

.container {
  max-width: 500px;
  margin: 0 auto;
  background: #fff;
}

.components {
  padding: 20px;
}

.components .content {
  margin-bottom: 20px;
}

.default {
  margin: 0 5px;
}

.switch {
  display: inline-block;
}

.switch input {
  display: none;
}

.switch small {
  display: inline-block;
  width: 100px;
  height: 18px;
  background: #3a3a3a;
  border-radius: 5px;
  position: relative;
  cursor: pointer;
}

.switch small:after {
  content: "No";
  position: absolute;
  color: #fff;
  font-size: 11px;
  font-weight: 600;
  width: 100%;
  text-align: right;
  padding: 0 6px;
  box-sizing: border-box;
  line-height: 18px;
}

.switch small:before {
  content: "";
  position: absolute;
  width: 12px;
  height: 12px;
  background: #fff;
  border-radius: 50%;
  top: 3px;
  left: 3px;
  transition: .3s;
  box-shadow: -3px 0 3px rgba(0, 0, 0, 0.1);
}

.switch input:checked~small {
  background: #3fc55c;
  transition: .3s;
}

.switch input:checked~small:before {
  transform: translate(25px, 0px);
  transition: .3s;
}

.switch input:checked~small:after {
  content: "Yes";
  text-align: left;
}
<div class="container">
  <div class="components">
    <div class="content">
      <label class="switch default">
                <input type="checkbox">
                <small></small>
            </label>
    </div>
  </div>
</div>

Answer №3

One way to ensure you have distinct styles for enabled and disabled links is by assigning specific class names to them.

For styling:

.link_enabled {
    /* Styles for when the link is enabled */
}
.link_disabled {
    /* Styles for when the link is disabled */
}

As for the script:

$(document).on('click', '.switch', function () {
    var v = $(".switch").attr("isValue");
    if (v == 1) {
        $(".switch").attr("isValue", "0");
        $(".switch").removeClass("link_enabled").addClass("link_disabled");
        $(".dim").removeClass("disabled");
    }
    else {
        $(".switch").attr("isValue", "1");
        $(".switch").removeClass("link_disabled").addClass("link_enabled");
        $(".dim").addClass("disabled ");
    }
});

Answer №4

Just a quick note, the code provided is written in a simpler way using ES6 in JavaScript. It's worth mentioning that only JavaScript is used here and not jQuery.

document.querySelector('.switch').onclick = function(e) {
  this.dataset.status = this.classList.toggle('disabled')?'0':'1';

  console.clear();
  console.log('data-status value is :', this.dataset.status );
}
.switch>span {
  display: block;
  width: 68px;
  height: 68px;
  background-color: green;
  border-radius: 34px;
}

.switch.disabled>span {
  background-color: grey;
}
<div class="switch" data-status="1" ><span></span></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

Selenium Mouse/Pointer Display

Is there a way to visualize the selenium mouse movements during test execution? Can we display a windows cursor image or any kind of indicator like a dot or crosshair? I am currently working on implementing a drag and drop feature using Selenium and Java ...

What is the proper way to utilize useRef with HTMLInputElements?

Dealing with React and hooks: In my code, there is a MainComponent that has its own operations and content which refreshes whenever the value of props.someData changes. Additionally, I have designed a customized InputFieldComponent. This component generat ...

Guide to retrieving SQL data using Node.js with mysql2

I've decided to convert my code from Python to Node.js, and I'm encountering a problem when trying to retrieve data from SQL. In Python, it's simple to get the data, return it, and then use it in the code. Here is the Python code: def sql_g ...

Overcoming Challenges with Ajax Success in Bootstrap DataTable Modal

Recently, I created a webpage featuring a top fixed navbar and a CRUD datatable with pagination supported by buttons that trigger modals. However, I'm encountering an issue where upon clicking the delete button in the modal to remove a record, the mod ...

Tips for concealing information within a JSON response using Javascript

I have a JavaScript function that retrieves card information based on its first 6 digits (BIN). const getCardInfo = async (cardNumber, isLive = false) => { const binCode = cardNumber.substring(0, 6); const cachedData = sessionStorage.getItem(`bin_${ ...

Prevent Buttons from Being Clicked While Another is Active in Angular

I am facing a challenge with my Angular functions that enable search features. My goal is to allow only one feature to be selected at a time. /* Trauma Search functionality */ $scope.traumaSearch = false; $scope.traumaText = "Trauma Center"; $scope.togg ...

Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving. Within localStorage, I am storing the entire game state, where some of the sub-objects ...

Update the default arrow icon in the expand/collapse navigation bar

I need help changing the downward arrow in the code below to a fontawesome icon. I'm unsure about how to: 1. Remove the default arrow on the right of the parent node. 2. Use "+/-" symbols to represent the collapse state. It seems that the onclick c ...

How can we rearrange the newly added row from onRowAdd in Material Table to be displayed at the beginning of the section?

Title. According to the documentation for material table, when using editable with onRowAdd, the new row is always added at the bottom of the section. Is there a way to have it appear at the top instead? Alternatively, how can I add an onClick effect so t ...

Ensure that dynamically generated fields are verified whenever one of them is modified

I am working on a program that generates text boxes and drop down lists dynamically. I need to find a way to validate these fields only when one of them is changed. The validation should occur if a date is entered in the text box, it should then check if t ...

How to retrieve JSON data from unidentified objects using JQuery

I have made an AJAX call and received a JSON file as the response: [ { "LINKNAME": "Annual Training", "HITS": 1 }, { "LINKNAME": "In Focus Newsletter", "HITS": 1 }, { "LINKNAME": "NITA (secured)" ...

Changing font styles using the jMenu jQuery plugin: A step-by-step guide

I'm having trouble changing the font-family using CSS with jQuery's "jMenu" plugin. Here is the CSS I currently have: .jMenu{ position : absolute; top : 80px; left : 0px; width : 100%; display:table; margin:0; padding ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

Customize the border width and color of a specific column in HighCharts based on dynamic data

I am looking to dynamically change the border width and color of only one column in a basic column chart. Here is an example: var chartingOptions = { chart: { renderTo: 'container', type: 'column' }, xAxis: { categories: [ ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

Navigating the intricacies of platform-specific settings in JavaScript

Currently, I am in the process of transferring an application from one PHP-based CMS to another (such as Wordpress, Joomla, etc.). I have established classes that enable my code to function seamlessly on each platform without any alterations (so far so goo ...

How do I prevent my image slider from scrolling to the top of the page when I click next or prev?

<script> export default { name: "ImageSlider", data() { return { images: [ "https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg", "https://cdn.pixabay.com/photo/2016/02/17/2 ...

What is the best way to retrieve the value of a nested function in JavaScript?

I am currently working on a project that involves a function. function findParentID(parentName) { Category.findOne({ categoryName: parentName }, function (err, foundParent) { var parentID = foundParent.categoryID;    return parentID;<br> } ...

Is it possible to extract elements from a single list and insert them onto various pages?

Currently, I am retrieving items from a list using an ajax call. After constructing the HTML content, I insert these items onto a page. Now, I want to extract the same items and display them on another page with a different style. Is there a method to conn ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...