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

Guide on retrieving the response headers with jQuery and AJAX

Connection: keep-alive Content-Length: 2231 Content-Type: text/html; charset=utf-8 Date: Thu, 13 Sep 2018 07:37:46 GMT ETag: W/"8b7-XOXhf04O/VM7yxWQ561PEgxRfz8" x-auth: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YjlhMGEyM2Q0NmI3YjFmYTQzNWI ...

What steps can be taken in Javascript to handle a response status code of 500?

I am currently utilizing a login form to generate and send a URL (referred to as the "full url" stored in the script below) that is expected to return a JSON object. If the login details are accurate, the backend will respond with a JSON object containing ...

Discovering WebElements nested within other WebElements using WebdriverJS

Looking at this HTML structure <div> <div> <p class="my-element"></p> </div> <div> <div> <div> <p class="the-text"> I want to retrieve this text</p> </div> </div> <div> ...

Hoping for a swift ajax response from the identical function

Even though similar questions have been asked multiple times, I have gone through many of them and still haven't found a solution to my specific issue. I am currently using a Wizard Jquery Plugin that triggers a function onLeaveAStepFunction when a s ...

Ensuring equal spacing between elements that are defined as a percentage, utilizing padding and margin properties

I've been searching online for a while now, but I haven't been able to find a solution that fits my needs. What I'm trying to do is space out 4 divs equally, each with a width of 25% minus the margin. The challenge is ensuring that the last ...

Visualize data from ajax call in tabular format

I want to display the results of an SQL query in a table using AJAX. I have written code that executes the query during the AJAX call, but when I try to display these values in a table, it shows null values on the div tag. What could be the reason for this ...

Issue with Ajax/Json: "An object of type triggers a circular reference error when attempting to retrieve a list."

Recently, I encountered an issue with my server-side method that is triggered through JSON/Ajax. The method itself functions flawlessly and sends back a list as expected. However, I seem to have made an error in my JavaScript code, leading to the following ...

Guide on accessing CGI Script response using AJAX

Greetings, Here is the situation: I'm working on a login form. Once the submit button is clicked, it needs to trigger a CGI script called "someurl?userName=user&password=pwd". Depending on the response from the script, I should be able to navigat ...

When <tr> is used as a link with the target="_blank" attribute

I'm facing an issue with my HTML and jQuery code. I'm trying to make a table row act as a link, but I'm struggling to figure out how to add the target="_blank" attribute. Could someone assist me in resolving this? Below is the snippet of H ...

Transform the data format received from the AJAX request - modify the input value

I have a data variable that contains an object structured as follows: { "details": { "id": 10, "name": John Doe, "hobbies": [{ "id": 1, "name": "Football" }, { "id": 2, "name": "Badminton" }, ...

What's the best method for concealing components: using a class to hide or removing them from the

I am encountering difficulties in React as I try to add a class to a component after a specific time duration. My goal is to apply the "hidden" class to a loading image, changing it to display: none after a few seconds. However, despite my efforts, I keep ...

Tips for troubleshooting JavaScript errors in Internet Explorer 7 & 6 using Dreamweaver CS3

Is there a way to track and debug JavaScript errors in Internet Explorer 7 & 6 on web pages using Dreamweaver CS3? I am experienced with debugging in Visual Studio, but unsure how to do it in Dreamweaver CS3. ...

"ExceptionThrownByMoveTargetOutOfBounds in Selenium WebDriver for IE9 and Firefox

Having trouble with the FireFox/IE9 driver in Selenium? When using the Actions class and its moveToElement method, I keep encountering a MoveTargetOutOfBoundsException error. Despite trying different solutions like Coordinates, Point, and javascriptexecuto ...

Looking for assistance in identifying the cause of CSS malfunction in Internet Explorer

I am encountering some challenges with the CSS on my website. I developed the site without considering Internet Explorer, and now that I am trying to address IE bugs, it feels like a daunting task. How do you approach debugging in situations like these? ...

Failed commitments in JavaScript without a catch block (unhandled rejection)

When working on my project in VueJs JavaScript, I want to be able to see console messages if any of my Promises are not fulfilled and do not have a catch block. I attempted using the following code: Promise.reject("error!"); window.addEventListener(&apos ...

Can you update the `runtime` property to `segment` in the export config?

I'm currently working on setting up an upload API route within my application. /admin/upload However, when I attempt to console.log(req.file), it returns as undefined. This seems to be related to the following configuration: export const config = { ...

How to Make a Div Tag Fade Effect with JavaScript in an External File

*** New Team Member Notice *** I'm currently working on an assignment and trying to implement a simple fade effect on a box. While it seems like this should be straightforward, I'm encountering some obstacles. Currently, the button causes the bo ...

How do you update the bind value in VueJs when using :value="text"?

My attempts at updating a string when the content is changed inside a textarea are not successful. Vue component: <template> <div> <textarea :value="text" @change="changed = true" @keyup="changed = true"&g ...

The personalized confirmation dialog is experiencing malfunctions

I have designed my own custom dialogs using Bootstrap and jQuery, such as Alert and ConfirmDialog. Here is a sample: http://jsfiddle.net/eb71eaya/ The issue I am facing is that in the callback function, I make an AJAX call. If it returns true, I want to ...

Tips for organizing a search using two keys in Javascript

I am dealing with a large dataset containing over ten thousand objects that hold information about two different ids as shown below: dataSet = [ { ids: ["123", "234"], information: 1 }, { ids: ["123", "345"], in ...