how to uncheck all Toggle Switch when one toggle switch is checked? - javascript

can someone tell me how can I change the other Toggle Switches to unchecked when I checked one of the toggle switch. I can do with checkbox but I found it very tricky with Javascript Toggle Switch
if (this.checked) {
$(":checkbox[value=switch-intermediate]").removeAttr("checked", null);
$(":checkbox[value=switch-expert]").removeAttr("Checked",null);
}
My code above works with checkbox but not Toggle Switch. I did see some other examples online from slack overflow like this one - Uncheck or turn off all checkbox based toggle switches when a new one is turned on?
But when I follow it, it still doesn't work. Thank you!
[jfiddle] (https://jsfiddle.net/jt100/4xjf1ano/3/)

With simple change event and .not(this)
By using $(".switch:not([checked])") no need to check if(this.checked)
To change checked/unchecked use .prop("checked" , true/false)
To prevent this checkbox from unchecked when unchecked others use .not(this)
$(".switch:not([checked])").on('change' , function(){
$(".switch").not(this).prop("checked" , false);
});
.switch-label {
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: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .slider {
background-color: #5c13ec;
}
input:focus + .slider {
box-shadow: 0 0 1px #5c13ec;
}
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://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle-two">
<div>Novice</div>
<label class="switch-label">
<input class="switch" id="switch-novice" value="switch-novice" type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
<div class="toggle-three">
<div>Intermediate</div>
<label class="switch-label">
<input class="switch" id="switch-intermediate" value="switch-intermediate" type="checkbox"/>
<span class="slider round"></span>
</label>
</div>
<div class="toggle-four">
<div>Expert</div>
<label class="switch-label">
<input class="switch" id="switch-expert" value="switch-expert" type="checkbox" />
<span class="slider round"></span>
</label>
</div>
Also if you've more switch s on another places .. you can use $(this).closest('CONTAINER').find('.switch').not(this)........ instead of $('.switch').not(this)..... SEE Example HERE

Change the inputs from checkboxes to radio buttons, and add a name="something" to each radio button, using the same "something" name on all the related buttons.
Basically, each input changes from this
<input class="switch" id="switch-novice"
value="switch-novice" type="checkbox" />
to this
<input class="switch" id="switch-novice"
value="switch-novice" type="radio" name="switch-choice" />
I have updated your fiddle

Related

How to save on off conditions in a switch to a variable

Not sure a similar question has been asked before. If so please point it out.
Of course I am new to this field. So please bear with me.
I have a html webpage which contains 6 switches.
I need to save on and off conditions of those switches into different variables.
on = 1
off = 0
As an instance, switch 1 on/off conditions represents x variable.
when on x=1 off x=0
switch 2 on/off conditions represents y variable.
when on y=1 off y=0
my page views as follows.
My code:
.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: #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 name="s" class="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox">
</label>
<label class="switch">
<input type="checkbox" checked>
</label>
Can someone help me to save these switch conditions into different variables? I would really appreciate it.
Thanks heaps!
Create a JavaScript function to handle the switch change:
<script type="text/JavaScript">
var switchValues = { };
function switched (switchElement) {
switchValues[switchElement.id] = switchElement.checked;
}
</script>
Then make sure each of your checkbox switches has a unique id attribute and onclick handler assigned to your new function:
<label name="s" class="switch">
<input type="checkbox" id="switch1" onclick="switched(this)" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" id="switch2" onclick="switched(this)" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" id="switch3" onclick="switched(this)" checked>
<span class="slider"></span>
</label><br><br>
<label class="switch">
<input type="checkbox" id="switch4" onclick="switched(this)" checked>
<span class="slider"></span>
</label><br><br>
Etc...
I have added the use of LocalStorage to keep switch positions
values are inside switchList object:
const switchList =
{​ switch_1: true
,​ switch_2: true
,​ switch_3: true ​
, switch_4: true
,​ switch_5: true
,​ switch_6: true
}
diretly build from the input checkbox list
You also need a form!
so when form element get any input change, by using event delegation you can set the checkbox value inside the switchList
then the switchList is copied into local storage
const switchersF = document.querySelector('form#switchers')
, memoSwitch = 'SwitchStorage'
, switchList = [...switchers.querySelectorAll('input[type=checkbox]')].reduce((s,el)=>{ s[el.name]=true;return s},{})
;
initSwitchs()
;
switchersF.onsubmit=e=>e.preventDefault() // disable submit form
;
switchersF.oninput=e=>
{
if (!e.target.matches('input[type=checkbox]')) return
switchList[e.target.name] = e.target.checked
setSwitchsMemo()
// console.log( switchList )
}
function initSwitchs()
{
let SwitchsMemo = localStorage.getItem(memoSwitch)
if (!SwitchsMemo)
{ setSwitchsMemo() }
else
{
for (let [key, value] of Object.entries( JSON.parse(SwitchsMemo) ))
{
switchersF[key].checked = value
}
}
}
function setSwitchsMemo()
{
localStorage.setItem(memoSwitch, JSON.stringify(switchList) )
}
#switchers label {
position: relative;
display: block;
float: left;
clear: both;
width: 60px;
height: 34px;
margin: .5em 1em;
}
#switchers input {
display: none;
}
#switchers span {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
#switchers span:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
#switchers input:checked+span {
background-color: #2196F3;
}
#switchers input:checked+span:before {
transform: translateX(26px);
}
#switchers input:focus+span {
box-shadow: 0 0 1px #2196F3;
}
<h2>Toggle Switch</h2>
<form id="switchers">
<label> <input type="checkbox" checked name="switch_1"> <span></span> </label>
<label> <input type="checkbox" checked name="switch_2"> <span></span> </label>
<label> <input type="checkbox" checked name="switch_3"> <span></span> </label>
<label> <input type="checkbox" checked name="switch_4"> <span></span> </label>
<label> <input type="checkbox" checked name="switch_5"> <span></span> </label>
<label> <input type="checkbox" checked name="switch_6"> <span></span> </label>
</form>

toggle switch back to off

I trying to create a function which reverts toggle switches back to off.
I'm turning a light on or off with my switch but there is a button and if i press that I want all the lights to turn off and the switches to turn to 'off'
As you can see there are 4 switches and a button to shut everything down. And I'm wondering how I can communicate between HTML, CSS and JS
<label class="switch">
<input type="checkbox" name="one" id="one">
<span class="slider round">
</span> </label>
<label class="switch">
<input type="checkbox" name="two" id="two">
<span class="slider round">
</span> </label>
<label class="switch">
<input type="checkbox" name="three" id="three">
<span class="slider round">
</span> </label>
<label class="switch">
<input type="checkbox" name="four" id="four">
<span class="slider round">
</span> </label>
<br>
<input type="button" id="stop" value="Stop All" onclick="shutdown()"><br>
I have created an example app for you here. https://codesandbox.io/embed/lucid-brook-q6qsq
The idea is to use document.querySelectorAll and iterate over all the checkboxes and uncheck them. Here is the relevant code:
document.querySelector("#stop").addEventListener("click", () => {
const switches = document.querySelectorAll(".switch input");
for (let s of switches) {
s.checked = false;
}
});
I recommend you look up querySelectorAll
window.addEventListener("load", function() {
document.getElementById("stop").addEventListener("click", function() {
[...document.querySelectorAll(".switch input[type=checkbox]")].forEach(function(chk) {
chk.checked = false; // and perhaps add chk.onchange() if needed
});
});
});
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.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%;
}
<label class="switch">
<input type="checkbox" name="one" id="one">
<span class="slider round">
</span> </label>
<label class="switch">
<input type="checkbox" name="two" id="two">
<span class="slider round">
</span> </label>
<label class="switch">
<input type="checkbox" name="three" id="three">
<span class="slider round">
</span> </label>
<label class="switch">
<input type="checkbox" name="four" id="four">
<span class="slider round">
</span> </label>
<br>
<input type="button" id="stop" value="Stop All" /><br>
Alternative code for ancient browsers
var chks = document.querySelectorAll(".switch input[type=checkbox]");
for (var i=0;i<chks.length;i++) chks[i].checked = false;
in JavaScript you'll use the getElementsByClassName() method. You'll have to add a class to all of your checkboxes, alternatively you can use getElementsByTagName() to target the checkbox tags.
let switches = document.getElementsByClassName("checkboxClass");
then iterate thru the class with JavaScript
for (let i = 0; i < switches.length; i++) {
switches[i].checked = false;
}
this will turn them all off. you can put this in a function and call it whenever (onclick/onchange, etc.)
Hope this helps, good luck!

HTML main category dropdown selection and sub-category list

I have seen other questions asked where select and optgroup were given, but where more CSS styling is needed, is there a way to show the sub-categories from a menu created using radio inputs?
The snippet shows the menu animation that is required so select won't work here. I changed the HTML markup to radio inputs. Is it possible to toggle the associated sub-category div when the main-category is select?
$(".cat-dropdown .title :input").click(function() {
var $menu = $(this)
.parent()
.siblings(".cat-dropdown-menu");
if ($menu.height() > 0) {
closeMenu($menu);
} else {
openMenu($menu);
}
});
$(".cat-dropdown-menu .cat-item").click(function() {
var $menu = $(this).closest(".cat-dropdown-menu");
closeMenu($menu);
$menu
.closest(".cat-dropdown")
.find(".title span")
.text($(this).text())
.css("color", this.style.color);
});
function closeMenu($menu) {
$list = $menu.children(".cat-list");
$menu.closest(".cat-dropdown").toggleClass("closed");
$menu.css("height", 0);
$list.css("top", 0);
}
function openMenu($menu) {
$list = $menu.children(".cat-list");
$menu.closest(".cat-dropdown").toggleClass("closed");
$menu.css({
height: 75
});
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.cat-list input {
display: none;
}
.sub-list {
display: flex;
flex-direction: column;
}
.main1 {
border: 2px solid blue;
}
.main2 {
border: 2px solid red;
}
.cat-dropdown {
margin: 25px;
text-align: left;
color: #343c3f;
border: 1px solid #a2acb0;
}
.cat-dropdown.closed .cat-dropdown-menu {
margin-top: 0px;
}
.cat-dropdown.closed .cat-dropdown-menu .cat-item {
height: 0px;
}
.cat-dropdown.closed .title {
border-bottom: none;
}
.cat-dropdown.closed .title:after {
margin-top: -16px;
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-ms-transform: rotate(0deg);
-o-transform: rotate(0deg);
transform: rotate(0deg);
}
.cat-dropdown .title {
width: 100%;
position: relative;
height: 40px;
padding: 12px;
cursor: pointer;
border-bottom: 1px solid #d9e1e4;
}
.cat-dropdown .title:after {
display: block;
content: "▾";
position: absolute;
right: 14px;
margin-top: -16px;
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
.cat-dropdown .cat-dropdown-menu {
position: relative;
overflow: hidden;
max-height: 200px;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
transition: all 0.2s;
-webkit-box-sizing: "border-box";
-moz-box-sizing: "border-box";
box-sizing: "border-box";
}
.cat-dropdown .cat-list {
position: absolute;
top: 0;
width: 100%;
}
.cat-dropdown .cat-list .cat-item {
width: 100%;
height: 40px;
line-height: 40px;
border-bottom: 1px solid #d9e1e4;
padding: 0 12px;
vertical-align: top;
overflow: hidden;
cursor: pointer;
-webkit-transition: margin-top 0.5s, height 0.5s;
-moz-transition: margin-top 0.5s, height 0.5s;
transition: margin-top 0.5s, height 0.5s;
}
.cat-dropdown .cat-list .cat-item:hover {
background-color: #d9e1e4;
color: #343c3f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat-dropdown closed">
<div class="edit">
<label class="title">
<input class="edit-input1" type="checkbox"><span> Choose...</span>
</label>
<div class="cat-dropdown-menu">
<div class="cat-list" id="category">
<label class="cat-item" style="color:blue">
<input type="radio" name="cat1">Main 1</label>
<label class="cat-item" style="color:red">
<input type="radio" name="cat2">Main 2</label>
</div>
</div>
</div>
</div>
Sub Category:
<div id="subcategory">
<div class="sub-list main1" for="cat1">
<input type="radio" name="sub1" value="opt1">main1 opt1
<input type="radio" name="sub1" value="opt2">main1 opt2
<input type="radio" name="sub1" value="opt3">main1 opt3
</div>
<div class="sub-list main2" for="cat2">
<input type="radio" name="sub2" value="opt1">main2 opt1
<input type="radio" name="sub2" value="opt2">main2 opt2
<input type="radio" name="sub2" value="opt3">main1 opt3
</div>
</div>
https://codepen.io/moofawsaw/pen/LmLZeM
Is it possible to toggle the associated sub-category div when the
main-category is select?
Yes, and this what worked for me:
function toggleSubcatDiv( input ) {
var name = $( input ).attr( 'name' );
$( '.sub-list[for="' + name + '"]' )
.siblings( '.sub-list' )
.filter( '.active' )
.removeClass( 'active' )
.end()
.end().addClass( 'active' );
}
Where I used the function in this closure:
$(".cat-dropdown-menu .cat-item").click(function() {
var $menu = $(this).closest(".cat-dropdown-menu");
closeMenu($menu);
// ... your code here.
toggleSubcatDiv( $( ':radio', this ) ); // <- here's where I used that function
});
Then I added this custom CSS:
.sub-list:not(.active) {
display: none;
}
So toggleSubcatDiv() will either add or remove active from the class attribute of the sub-category div (i.e. .sub-list).
See demo on https://codepen.io/anon/pen/NMyKvp (PS: I did not change the HTML markup; however, you could pre-select the Main 1 div by adding active to the class of that div.)
UPDATE
In reply to your comment, this should work so long as the sub-category divs are placed in (or added to) the same .container div:
function toggleSubcatDiv( input ) {
var name = $( input ).attr( 'name' );
$( '.sub-list[for="' + name + '"]' )
.closest( '.container' )
.find( '.sub-list.active' )
.removeClass( 'active' )
.end()
.end().addClass( 'active' );
}
So what changed is, that we now find the closest parent/container which is shared by the sub-category divs.
Demo: https://codepen.io/anon/pen/LmQoRg
I once had to do something similar, this was what I came up with:
<script>
function subselect(cat){
var select = "";
if (cat == 1) {
select = "<select><option value='a1'>a1</ooption><option value='a2'>a2</ooption></select>"
}else if (cat == 2) {
select = "<select><option value='b1'>b1</ooption><option value='b2'>b2</ooption></select>"
}
document.getElementById("subcategory").innerHTML = select;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cat-dropdown closed">
<div class="edit">
<label class="title">
<input class="edit-input1" type="checkbox"><span> Choose...</span>
</label>
<div class="cat-dropdown-menu">
<div class="cat-list" id="category">
<label class="cat-item" style="color:blue">
<input type="radio" name="cat" onclick='subselect(1)'>Main 1</label>
<label class="cat-item" style="color:red">
<input type="radio" name="cat" onclick='subselect(2)'>Main 2</label>
</div>
</div>
</div>
</div>
Sub Category:
<div id="subcategory">
</div>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
select optgroup{
display: none;
}
input.a:checked + input + select optgroup[label=a]{
display: block !important;
}
input.b:checked + select optgroup[label=b]{
display: block !important;
}
</style>
</head>
<body>
a<input class="a" type="checkbox" name="sel" value="a">
b<input class="b" type="checkbox" name="sel" value="b">
<select class="" name="">
<optgroup label="a">
<option value="a1">a1</option>
<option value="a2">a2</option>
</optgroup>
<optgroup label="b">
<option value="b1">b1</option>
<option value="b2">b2</option>
</optgroup>
</select>
</body>
</html>
This is an example of how you could alter a list using the :checked psuedo selector. When using psuedo selectors you need to be able to navigate to the element you want to alter. Our input.a has to traverse to its second sibling, but input.b only has to travers to its first.

How to set a div (custom Radio-Button and Checkbox) as required?

I want to create custom and accessible Radio- and Checkbox-Buttons and found the nice solution of W3C, using divs and aria role="radio".
https://www.w3.org/TR/2017/NOTE-wai-aria-practices-1.1-20171214/examples/radio/radio-1/radio-1.html
<div role="radiogroup" aria-labelledby="group_label_1" id="rg1">
<h3 id="group_label_1">Label</h3>
<div role="radio" aria-checked="false" tabindex="0">
Button
</div>
</div>
It looks and works great for me, but I want to implement Radio-Buttons as required fields of the form. Problem: in this solution is no input-element and for this reason no required-attribute possible..
The WAI-ARIA aria-required property indicates that user input is required before submission. The aria-required property can have values of "true" or "false". For example, if a user must fill in an field, then aria-required is set to "true".
<div role="radiogroup" aria-labelledby="group_label_1" aria-required="true" id="rg1">
<h3 id="group_label_1">Label</h3>
<div role="radio" aria-checked="false" tabindex="0">
Button
</div>
</div>
you only make it require with add a property
aria-checked = true
into first any radio.
ex:
<div role="radiogroup" aria-labelledby="group_label_1" id="rg1">
<h3 id="group_label_1">Label</h3>
<div role="radio" aria-checked="true" tabindex="0">
Button
</div>
<h3 id="group_label_2">Label2</h3>
<div role="radio" aria-checked="false" tabindex="1">
Button2
</div>
</div>
Check W3school custom radio button for creating custom radio buttons. and you can put required attribute to radio buttons check the following code for the demo.
<!DOCTYPE html>
<html>
<style>
/* The container */
.container {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default radio button */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* Create a custom radio button */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
}
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
background-color: #ccc;
}
/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark {
background-color: #2196F3;
}
/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after {
display: block;
}
/* Style the indicator (dot/circle) */
.container .checkmark:after {
top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
}
</style>
<body>
<h1>Custom Radio Buttons</h1>
<form method="post" action="https://facebook.com" target="_blank">
<label class="container">One
<input type="radio" required="" name="radio">
<span class="checkmark"></span>
</label>
<label class="container">Two
<input type="radio" name="radio" required="">
<span class="checkmark"></span>
</label>
<input type="submit" value="asd" />
</form>
</body>
</html>
You can simply add the required tag to your input elements.
Here's a working CodePen: https://codepen.io/anon/pen/zWzaKM

Replace two buttons with a toggle switch

I have the following code:
<img id="v1" src="pic1.jpg"><br>
<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>
<br>
<img id="v2" src="pic3.jpg"><br>
<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>
<br>
However, I would like to replace these 'Before' and 'After' buttons with a toggle switch (already made) in the form of a checkbox:
<label class="switchBA">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
In a way that each time it's clicked it switches between the two functions. I guess this needs to be done inline since these are just two of many comparisons.
Thanks in advance.
P.S: I would like to do with only with JS. No need for jQuery or other frameworks.
Here's a nice way to achieve this by listening for the toggle in javascript and setting the image to that of the custom data attribute set under the image tag.
var toggleClass = document.getElementsByClassName("toggle");
var toggleFunction = function() {
var imageElement = this.parentElement.parentElement.getElementsByClassName("imageItem")[0];
if(this.checked){
imageElement.src = imageElement.getAttribute("data-image-2");
}else{
imageElement.src = imageElement.getAttribute("data-image-1");
}
};
for (var i = 0; i < toggleClass.length; i++) {
toggleClass[i].addEventListener('click', toggleFunction, false);
}
.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);
}
<h2>Toggle Image Demo</h2>
<div class="imageContainer">
<img class="imageItem" src="https://lorempixel.com/400/200/sports/5/Image1/" data-image-1="https://lorempixel.com/400/200/sports/5/Image1/" data-image-2="https://lorempixel.com/400/200/sports/6/Image2/">
<label class="switch">
<input class="toggle" type="checkbox">
<span class="slider"></span>
</label>
</div>
<div class="imageContainer">
<img class="imageItem" src="https://lorempixel.com/400/200/sports/5/Image1/" data-image-1="https://lorempixel.com/400/200/sports/5/Image1/" data-image-2="https://lorempixel.com/400/200/sports/6/Image2/">
<label class="switch">
<input class="toggle" type="checkbox">
<span class="slider"></span>
</label>
</div>
Taking this approach over CSS and Backgrounds or setting the second image URL in the javascript should help keep the code cleaner. Also by doing this, the code will be easier to scale to accommodate multiple images toggles on one page without changing the Javascript.
Try this.
function toggleImage(){
var el = document.getElementById("toggle")
if(el.checked){
document.getElementById("v1").src="https://picsee.co/images/social_facebook.png";
}
else{
document.getElementById("v1").src="https://picsee.co/images/social_twitter.png";
}
}
<img id="v1" src="https://picsee.co/images/social_facebook.png">
<label class="switchBA">
<input type="checkbox" id="toggle" checked onclick="toggleImage()">
<span class="slider"></span>
</label>
You can use onchange event to get the event on state change as below
function oncheckchange(e)
{
console.log(event.currentTarget.checked)
if(event.currentTarget.checked)
document.getElementById('v2').src='pic4.jpg'
else
document.getElementById('v2').src='pic3.jpg'
}
<img id="v1" src="pic1.jpg"><br>
<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>
<br>
<img id="v2" src="pic3.jpg"><br>
<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>
<br>
<label class="switchBA">
<input type="checkbox" checked onchange="oncheckchange()">
<span class="slider"></span>
</label>
The simplest way to do this is to set the image as the background image of an element and then toggle that CSS setting by toggling the class that defines it:
document.querySelector("input[type=checkbox]").addEventListener("click", function(){
document.querySelector(".slider").classList.toggle("otherImage");
});
div {
width:150px;
height:150px;
background-size:contain;
border:1px solid black;
}
/* This will be the default style used because the class is defined in the HTML */
.slider {
background-image:url("http://aws-cdn-01.shemazing.ie/wp-content/uploads/2015/09/disappointed-but-relieved-face.png");
}
/* This will be toggled on and off by the clicking of the checkbox. When it is
toggled on, it will override the previous background-image value. */
.otherImage {
background-image:url("https://au.res.keymedia.com/files/image/emoji.jpg");
}
<label class="switchBA">
<input type="checkbox" checked>
<div class="slider"></div>
</label>
First of all you should never execute code in a handler the way you do. It's doable but in terms of readibility and maintainability it sucks, the handlers should only be used to fire a function.
It's fairly simple to achieve what you want.
put the toggle code inside a div and put the image and the newly created div inside a container div.
The div holding the toggle should include "display:none" in the css from the beginning so it is not shown, once you click on the button, you just need to hide the image and show the toggle switch div by changing "display:none" to "display:block";
Something like
<div class="container">
<img id="image1"src="https://openclipart.org/download/216413/coniglio_rabbit_small.svg" alt="">
<div id="toggle">
<img id="image2"src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/sign-check-icon.png" alt="">
</div>
<button onclick="Change()">Click me</button>
</div>
https://codepen.io/anon/pen/rYGMYx

Categories