Tips for implementing a function within a toggle button

I am looking to enhance the functionality of a toggle button when it is changed. Currently, there is no action associated with the toggle change event. I want to create a method that will be executed when the toggle is switched on or off. Additionally, I need to display and hide certain links based on the toggle change. Below is a sample code snippet (CSS and HTML). Can someone please assist me in writing the necessary syntax?

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

.switch input {
  display: none;
}

.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: #2196F3;
}

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

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%;
}
<h2>Toggle Switch</h2>
<label class="switch">
  <input type="checkbox" checked>
  <span class="slider round"></span>
</label>

Answer №1

To implement a simple functionality using plain JavaScript, you can add an onchange function to a checkbox input element and toggle the display property of a link based on its checked status. The following function checks the state of the checkbox when it is clicked - if checked, it displays the link as a block element, and if unchecked, it hides the link.

function toggleCheck() {
  if(document.getElementById("myCheckbox").checked === true){
    document.getElementById("aLink").style.display = "block";
  } else {
    document.getElementById("aLink").style.display = "none";
  }
}
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}
/* CSS code for toggle switch */
<h2>Toggle Switch</h2>
<label class="switch">
  <input type="checkbox" id="myCheckbox" onchange="toggleCheck()" checked>
  <span class="slider round"></span>
</label>
<a id="aLink" href="" style="display:block;">Link</a>

Answer №2

$('#toggle').on('click', function(){
    if ( $(this).is(':checked') ) {
        $('#link').show();
    } 
    else {
        $('#link').hide();
    }
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  display: none;
}

.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: #2196F3;
}

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

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%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>Toggle Switch</h2>
<label class="switch">
  <input id="toggle" type="checkbox" checked>
  <span class="slider round"></span>
</label>
<br/>
<a href="www.stackoverflow.com" id="link">Link</a>

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

Internet Explorer does not recognize the specific CSS code

My goal is to create a website that behaves differently on Internet Explorer browser. I am attempting to achieve this by using a separate CSS for IE and another CSS for different browsers. However, the IE-specific CSS does not seem to be working. <h ...

Issue with custom select functionality on Internet Explorer 9

Having some issues with a select element in IE9. The links that should open the wiki page are not functioning properly only on IE9, and there is also an issue with the hover effect - the icon gets overridden by the background color when hovering over help ...

The v-show directive is not activated by a Vuex commit

I am experimenting with vuex for the first time, and I have come across an issue where a v-show directive is not triggering after a mutation commit on the store. // store.js import Vue from "vue" import Vuex from "vuex" const states = ...

What is the best method to smoothly navigate to a specific id on a webpage after conducting a search using

I want to implement a jQuery function that allows me to scroll down to an id containing search results. The script as a whole, minus the JS, is functioning properly. I just need assistance in creating a method to search for specific id values. Below is my ...

The Facebook JavaScript API function FB.api() is limited to posting messages and does not support media attachments

I am attempting to share a message with an mp3 attachment on the active user's wall. It works perfectly fine within Facebook's Test Console, but when I try it from my mobile app, only the message gets posted. Can anyone help me figure out what I ...

How to partially load a webpage using jQuery

I run a wordpress site and I'm trying to use jquery to load my pages. Specifically, I want to load only the content div. To achieve this, I pass the URL like so: var url = $(this).attr('href') + "#content"; The issue arises when I attempt ...

Converting a data-attribute list into an array

My current setup includes an image with the following properties: <img id="img" data-list="['image2.jpg', 'image3.jpg', 'image4.jpg']" src="image1.jpg"> I am wondering how I can extract the list of images from the data ...

Using Angular JS to connect Promises while preserving data

There have been discussions about chaining promises, but this scenario presents a unique challenge. I am currently working on making multiple http get requests in my code. The initial call returns an array, and for each object in this array, another http c ...

The node.js oauth-1.0a implementation is successful in authenticating with Twitter API v1.1, however, it encounters issues

Having come across this function for generating an oauth-1.0a header: // auth.js const crypto = require("crypto"); const OAuth1a = require("oauth-1.0a"); function auth(request) { const oauth = new OAuth1a({ consumer: { key ...

Removing item from Angular service

Within my Angular 2 application, I have created a service called events.service.ts: const EVENTS = { 1512205360: { event: 'foo' }, 1511208360: { event: 'bar' } } @Injectable() export class EventsService { getEvents() ...

The sorting function in Vue.js, _.orderBy, seems to be having trouble sorting

UPDATE This is the json data retrieved through an API using axios. bannerData= [ { "id": 118, "title": "Geruchsbel\u00e4stigung", "location": "DOR", "pressInformation": [ { ...

How come the mouseover effect on the div remains even after the mouse has been removed?

How can I keep the original CSS class when the mouse moves away? function highlight( x, y) { var sel=document.getElementById(y); sel.style.borderBottom= "2px solid "+x; sel.style.opacity="1"; sel.style.transition="all eas ...

Dealing with Sideways Overflow Using slideDown() and slideUp()

Attempting to use slideUp() and slideDown() for an animated reveal of page elements, I encountered difficulty when dealing with a relatively positioned icon placed outside the element. During these animations, overflow is set to hidden, resulting in my ico ...

Is there a distinction between the values 'normal' and 'stretch' in the CSS property known as 'align-content'?

When it comes to the CSS declaration 'align-content', the default value is 'normal'. But, there is also another option: 'stretch'. I have been having a hard time figuring out if there is any actual difference between the two. ...

Permanent Visibility of Bootstrap 4 Navbar Toggler Icon

I am facing an issue with my navbar-toggler as it remains visible even on a large screen where it is not needed. To view the file, click here. <div class="navbar-header"> <a href="#" class="navbar-brand">Logo</a> </di ...

Game where two players take turns playing against each other

I'm facing a bit of a dilemma at the moment. I am in the process of creating a simple turn-based two-player game, and I have been experimenting with Node.js and Socket.IO based on recommendations from a question I found: Multiplayer JavaScript game ...

Ways to create distance between DIV elements?

On my WordPress generated page, I am looking to add AdSense below the header. You can view an image of the layout here. I have attempted to create space between the header and the AdSense ad by applying margin-top and padding to the div that contains the ...

Mongoose exploring the use of promises to manage pre-save errors

I'm facing an issue with using pre-save to handle errors for existing users or emails. When I remove the pre-save block, everything works fine, but I get the default mongoose error for duplicates due to using the Unique feature in my schema. I want t ...

rails neglecting to include in the array

Could someone help me with this block of code I have: doc.xpath("//script[@type='text/javascript']/text()").each do |text| if text.content =~ /more_options_on_polling/ price1 = text.to_s.scan(/\"(formatted_total_price)\ ...

What is the method for adjusting the dimensions of a background image (height and width)?

Just beginning to dip my toes into the world of JavaScript. This is where I'm at with my code: $("#Stage").css( "background-image", "url(BG.jpg)", "background-attachment", "fixed" ); I'm aiming to adjust the background image dimensio ...