How to animate height of fadeIn & toggle & fadeOut - javascript

I would like to know how I could improve the code and how to animate the height of the fadeIn/toggle. There is a jerky movement to the height when you click a checkbox. I would like it to be a smooth slide up or down. I read that the jerky movement is because jquery doesn't know the height of the element being faded in or out. Am I on the right track?
MyCode:
jQuery('.checkbox').on('change', function() {
window.globalCheckboxValue = CheckBoxSwitch(jQuery(this).val());
jQuery('.checkbox').not(this).prop('checked', false);
});
function CheckBoxSwitch(choice) {
var text = "";
var $selectList = jQuery('.selecrWrapper');
var $datepicker = jQuery('.datepicker');
switch (parseInt(choice)) {
case 1:
text = "Pedagog";
if (!$datepicker.is(':visible') && !$selectList.is(':visible')) {
jQuery(".selecrWrapper").animate({ marginTop: "100px" }, 1000, function () {
$datepicker.fadeIn(1000);
});
}
if (!$datepicker.is(':visible') && $selectList.is(':visible')) {
$selectList.fadeToggle(600, function() {
$datepicker.fadeIn(1000);
});
}
break;
case 2:
text = "Arrendator";
if (!$datepicker.is(':visible') && !$selectList.is(':visible')) {
$datepicker.fadeIn(1000);
}
if (!$datepicker.is(':visible') && $selectList.is(':visible')) {
$selectList.fadeToggle(600, function() {
$datepicker.fadeIn(1000);
});
}
break;
case 3:
text = "Program";
if (!$selectList.is(':visible') && !$datepicker.is(':visible')) {
$selectList.fadeIn(1000);
}
if ($datepicker.is(':visible') && !$selectList.is(':visible')) {
$datepicker.fadeToggle(600, function() {
$selectList.fadeIn(1000);
});
}
break;
}
return text;
}
.calenderStyle {
margin-top: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="displayPedagog">
<span>
Pedagog:
</span>
<input type="checkbox" class="checkbox" value="1" />
</div>
<div class="marginArr">
<span>
Arrendator
</span>
<input type="checkbox" class="checkbox" value="2" />
</div>
<div class="marginProg">
<span>
Program
</span>
<input type="checkbox" class="checkbox" value="3" />
</div>
</div>
<div class="slectanddateWrapper">
<!-- DatePicker -->
<div class="datepicker" style="display:none;">PlaceHolderDatePicker</div>
<!-- DatePicker -->
<!-- SelectList -->
<div class="selecrWrapper" style="display:none;">
<label class="selectLabelProgram">Välj det program du tillhör: </label>
<select class="form-control selectProgram" id="selectList"></select>
</div>
<!-- SelectList -->
</div>
<div class="calenderStyle">
<!-- calender -->
<div id='calendar'>CalenderPlaceHolder</div>
<!-- calender -->
</div>

The height difference is happening because the <select/> has more height than the <span/>.
You can try using slideUp() or slideDown() to achieve a smoother transition.
If you prefer using toggle, you can use slideToggle().

Related

How to show and hide div elements using vanilla js

Below is code where i tried to show and hide div elements using pure js. Since when i click button it take three click to hide the div elemnts and after that it run smoothly. I was trying to find how to show elemnts in first click.
var count = 0;
function showMee() {
var buttonHome = document.querySelector("#showMe");
count += 1;
buttonHome.addEventListener("click", function() {
if (count == 1) {
document.querySelector('#linkMeOne').style.display = 'none';
document.querySelector('#linkMeTwo').style.display = 'none';
} else if (count == 2) {
document.querySelector('#linkMeOne').style.display = 'block';
document.querySelector('#linkMeTwo').style.display = 'block';
count = 0;
}
});
}
#linkMeOne {
display: block;
}
#linkMeTwo {
display: block;
}
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" onclick="showMee()" />
Just toggle hidden.
If you want them to start out hidden, add the hidden attribute to the divs
const div1 = document.getElementById("linkMeOne");
const div2 = document.getElementById("linkMeTwo")
document.querySelector("#showMe").addEventListener("click",function() {
div1.hidden = !div1.hidden;
div2.hidden = !div2.hidden;
})
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" />
Just remove the addEventlistener and the code will start working.
var count = 0;
function showMee() {
var buttonHome = document.querySelector("#showMe");
count += 1;
//buttonHome.addEventListener("click", function() {
if (count == 1) {
document.querySelector('#linkMeOne').style.display = 'none';
document.querySelector('#linkMeTwo').style.display = 'none';
} else if (count == 2) {
document.querySelector('#linkMeOne').style.display = 'block';
document.querySelector('#linkMeTwo').style.display = 'block';
count = 0;
}
//});
}
#linkMeOne {
display: block;
}
#linkMeTwo {
display: block;
}
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" onclick="showMee()" />
Instead of using a variable, use a class to set the display to none.
function showMee() {
document.querySelector('#linkMeOne').classList.toggle('hidden');
document.querySelector('#linkMeTwo').classList.toggle('hidden')
}
#linkMeOne {
display: block;
}
#linkMeTwo {
display: block;
}
.hidden {
display: none !important;
}
<div id="linkMeOne">
Hiding me As first time....
</div>
<div id="linkMeTwo">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" onclick="showMee()" />
While there are many correct answers, all of them lack simplicity.
The easiest of all solution is to add an eventListener to the button and toggle a class to all elements with a certain class. That way you don't have to list every single element:
document.querySelector('#showMe').addEventListener('click', function() {
document.querySelectorAll('.linkMe').forEach(el =>
el.classList.toggle('d-block')
);
})
.linkMe {
display: none;
}
.d-block {
display: block;
}
<div class="linkMe">
Hiding me As first time....
</div>
<div class="linkMe">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" />
You could just toggle using a data attribute and some CSS. Here is a verbose version of that:
document.querySelector("#showMe")
.addEventListener("click", (event) => {
const t = event.target;
const showem = t.dataset.show;
document.querySelectorAll('.can-toggle').forEach((element) => {
element.dataset.show = showem;
});
t.dataset.show = showem == "show" ? "hide" : "show";
});
.can-toggle[data-show="hide"] {
display: none;
}
<div class="can-toggle">
Hiding me As first time....
</div>
<div class="can-toggle">
Hiding me as well as...
</div>
<input type="button" value="Check Me" id="showMe" data-show="hide" />
OR even independently with an initial state:
document.querySelector("#showMe")
.addEventListener("click", (event) => {
document.querySelectorAll('.can-toggle').forEach((element) => {
element.dataset.show = element.dataset.show == "hide" ? "show" : "hide";
});
});
.can-toggle[data-show="hide"] {
display: none;
}
<div class="can-toggle" data-show="hide">
Hiding me As first time....
</div>
<div class="can-toggle">
Hiding me as well as...
</div>
<div class="can-toggle" data-show="Ishow">
What am I?
</div>
<input type="button" value="Check Me" id="showMe" data-show="hide" />

i cant change the bg-color of cards when i toggle

Here's the part of HTML code:
<div class="card box bds">
<div class="card-body text-center">
<p class="text">
<img src="images/icon-facebook.svg" alt="fb" class="img" />#nathanf
</p>
<h1>1987</h1>
<pre>F O L L O W E R S</pre>
<p class="trend">
<img src="images/icon-up.svg" alt="up" class="img1" />12 Today
</p>
</div>
</div>
and I created the switch button (it works fine):
<div>
<h4>Social Media Dashboard</h4>
<p class="switch-text">Dark Mode</p>
<div class="custom-control custom-switch mode">
<input
type="checkbox"
class="custom-control-input"
id="customSwitch"
onclick="myFunction()"
/>
<label class="custom-control-label" for="customSwitch"></label>
</div>
<p class="followers">Total Followers: 23,004</p>
</div>
This is the background color that I've added in light theme using css:
.box {
background-color: hsl(227, 47%, 96%);
}
and this is what I want to add after button is clicked:
.dark-box {
background-color: hsl(228, 28%, 20%);
}
here's the JS code:
function myFunction() {
var element = document.body;
var element1 = document.class('.card');
element.classList.toggle('dark-mode');
element1.classList.toggle('dark-box');
}
Now, when I click the switch the cards background-color remains the same, it won't change I want it to change to .dark-box theme, plz help
document.class is not a valid function.
use one of these instead:
document.querySelector('.card'): returns the first element of class = card
document.querySelectorAll('.card'): returns all the elements of class = card
document.getElementsByClassName('card'): returns all the elements of class = card
And to apply the dark-box class to every one of the cards, you can do this:
function myFunction() {
const body = document.querySelector('body');
const cards = document.querySelectorAll('.card');
body.classList.toggle('dark-mode');
cards.forEach(card => card.classList.toggle('dark-box'));
}
There is nothing called document.class() in javascript, you can use querySelector() instead.
function myFunction() {
var element = document.body;;
var element1 = document.querySelector('.card');
element.classList.toggle("dark-mode");
element1.classList.toggle("dark-box");
}
.box {
background-color: hsl(227, 47%, 96%);
}
.dark-box {
background-color: hsl(228, 28%, 20%);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="card-deck">
<div class="card box bds">
<div class="card-body text-center">
<p class="text"><img src="images/icon-facebook.svg" alt="fb" class="img">#nathanf</p>
<h1>1987</h1>
<pre>F O L L O W E R S</pre>
<p class="trend"><img src="images/icon-up.svg" alt="up" class="img1">12 Today</p>
</div>
</div>
<div>
<h4>Social Media Dashboard</h4>
<P class="switch-text">Dark Mode</P>
<div class="custom-control custom-switch mode">
<input type="checkbox" class="custom-control-input" id="customSwitch" onclick="myFunction()">
<label class="custom-control-label" for="customSwitch"></label>
</div>
</div>
<p class="followers">Total Followers: 23,004</p>
</div>
</body>
</html>
you can pass event to your myFunction at onclick event handler.and then you can use it to toglle classList.Here is a quick example from codepen.
<div class="bg-change" onclick="myFunction(event);"></div>
.bg-change {
width:400px;
height:200px;
border:1px solid #000;
}
.dark-mode {
background:darkblue;
}
function myFunction(event) {
const { classList } = event.target;
classList.toggle("dark-mode");
}
you can play with it and change it according to your situation.
https://codepen.io/jesusfellas/pen/VwvjgrW
i found a solution, just edited the js code:
function darktheme() {
document.querySelector('body').classList.toggle("dark-mode");
document.querySelectorAll('.box')[0].classList.toggle("dark-box");
document.querySelectorAll('.box')[1].classList.toggle("dark-box");
document.querySelectorAll('.box')[2].classList.toggle("dark-box");
document.querySelectorAll('.box')[3].classList.toggle("dark-box");
document.querySelectorAll('.box')[4].classList.toggle("dark-box");
document.querySelectorAll('.box')[5].classList.toggle("dark-box");
document.querySelectorAll('.box')[6].classList.toggle("dark-box");
document.querySelectorAll('.box')[7].classList.toggle("dark-box");
document.querySelectorAll('.box')[8].classList.toggle("dark-box");
document.querySelectorAll('.box')[9].classList.toggle("dark-box");
document.querySelectorAll('.box')[10].classList.toggle("dark-box");
document.querySelectorAll('.box')[11].classList.toggle("dark-box");
}
But still is there any way to make it shorter?

How can I toggle texts and icons using jQuery?

I have an accordion.
When I click on show details :
the accordion content will expand,
the text will change from show details to hide details
the icon will change from + to x
click on it again should toggle back to its original state.
I couldn't get it to work. When I click on it, it stuck on the HIDE DETAILS state forever.
JS
$(".show-details-sk-p").click(function () {
$(".show-details-txt-sk-p-r").text("HIDE DETAILS");
$(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/e9eydpbct/remove.png");
});
Can someone please give me a little push here ?
I've put together a Fiddle - just in case it is needed.
Inspected the aciton and element behavior, find that #sk-p-r will have class in to decide whether its collapsed or not.
$(".show-details-sk-p").click(function () {
var isCollapse = $('#sk-p-r').hasClass('in');
var text = isCollapse ? 'SHOW DETAILS' : 'HIDE DETAILS';
var img = isCollapse ? 'http://s6.postimg.org/e9eydpbct/plus.png' : 'http://s6.postimg.org/bglqtob0d/remove.png'
$(".show-details-txt-sk-p-r").text(text);
$(".icon-sk-p-r-toggle").attr("src", img);
});
There's a lot of ways you can do this but your problem is that your 'click' doesn't have any way to set the 'show details' state from the code you have there.
In a really simple solution for this:
$(".show-details-sk-p").click(function () {
$(this).toggleClass('open')
if($(this).hasClass('open') === true){
$(".show-details-txt-sk-p-r").text("HIDE DETAILS");
$(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/e9eydpbct/remove.png");
}else{
$(".show-details-txt-sk-p-r").text("SHOW DETAILS");
$(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/bglqtob0d/plus.png");
}
});
This is one way to do it. I'm adding a class to the element here to track state and then conditionally setting the image and text based on that state to give you a true toggle. There are likely smarter and more efficient ways to do this but this should be a simple enough example to point you into the right direction.
I have added a boolean variable which is toggled whenever the accordion is clicked. Check out this fiddle
var show=false; //indicates whether the accordion is hidden
$(".show-details-sk-p").click(function () {
if(!show){
$(".show-details-txt-sk-p-r").text("HIDE DETAILS");
$(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/e9eydpbct/remove.png");
show=true;
}
else{
$(".show-details-txt-sk-p-r").text("SHOW DETAILS");
$(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/bglqtob0d/plus.png");
show=false;
}
});
I have used the show variable to determine what text to display on the accordion.
You need to revert text and image when collapsing an accordion
/* JavaScript */
$(".show-details-sk-p").click(function() {
if ($(this).data('shown') === true) {
$(this).data('shown', false);
$(".show-details-txt-sk-p-r").text("SHOW DETAILS");
$(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/bglqtob0d/plus.png");
} else {
$(this).data('shown', true);
$(".show-details-txt-sk-p-r").text("HIDE DETAILS");
$(".icon-sk-p-r-toggle").attr("src", "http://s6.postimg.org/e9eydpbct/remove.png");
}
});
/* CSS */
.sk-p-dash {
padding-left: 25px;
}
.panel {
border-radius: 0px !important;
}
.sk-p {
margin-right: 16px;
margin-left: 16px;
}
.panel-title,
.panel-body {
font-size: 10px;
}
.show-details-txt-sk-p-r {
padding-right: 12px;
}
.show-details-sk-p {
font-size: 9px;
padding-right: 5px;
}
.show-details-sk-p .icon-sk-p-r-toggle {
margin-top: -5px;
}
<!-- HTML -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="row sk-p">
<div class="col-md-12">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
PRE-REQUISITE(S) FOR ALL SKILLS IN EXERCISE
<span data-toggle="collapse" data-parent="#accordion" href="#sk-p-r" class="show-details-sk-p pull-right">
<span class="show-details-txt-sk-p-r">SHOW DETAILS</span>
<img width="20px" class="icon-sk-p-r-toggle" src="http://s6.postimg.org/bglqtob0d/plus.png">
</span>
</h4>
</div>
<div id="sk-p-r" class="panel-collapse collapse">
<div class="panel-body">
<div class="col-lg-6">
<span>SOLVING EQUATIONS BY ADDITION OR SUBSTRACTION </span>
<br>
<br>
<div class="sk-p-dash">
<img width="20px" class="icon-sk-p-r" src="http://s6.postimg.org/m4phsikzh/review_video.png">
<span>WATCH VIDEO</span>
<br>
<br>
<img width="20px" class="icon-sk-p-r" src="http://s6.postimg.org/6yjg1kuyl/review_pdf.png">
<span>REVIEW LESSON</span>
</div>
</div>
<div class="col-lg-6">
<span>GRAPHING INEQUALITIES IN ONE VARIABLE </span>
<br>
<br>
<div class="sk-p-dash">
<img width="20px" class="icon-sk-p-r" src="http://s6.postimg.org/m4phsikzh/review_video.png">
<span>WATCH VIDEO</span>
<br>
<br>
<img width="20px" class="icon-sk-p-r" src="http://s6.postimg.org/6yjg1kuyl/review_pdf.png">
<span>REVIEW LESSON</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Simply toggle
better store the string values in variables
var txtHide = "HIDE DETAILS";
var txtShow = "SHOW DETAILS";
var rmvImage = "http://s6.postimg.org/e9eydpbct/remove.png";
var plsImage = "http://s6.postimg.org/bglqtob0d/plus.png";
$(".show-details-sk-p").click(function () {
$(".show-details-txt-sk-p-r").text($(".show-details-txt-sk-p-r").text()==txtHide ? txtShow :txtHide );
$(".icon-sk-p-r-toggle").attr("src",$(".icon-sk-p-r-toggle").attr("src")==rmvImage ? plsImage :rmvImage );
});
Check http://jsfiddle.net/ZigmaEmpire/bpaxpuhz/2/

Javascript roll over and hide parts of page

I have an issue with the roll over and change the cursor to a hand on a hover over two images here is the code I use for the hide/display:
<div class="listing">
<span style="float:right; margin:-10px 100px 0px 20px;">Change view: </span>
<input class="listing" id="List" style="visibility: hidden;" name="listing" onclick="hideForm()" type="radio">
<label class="listing" for="List">
<img src="/devsite/images/icons/row.png" alt="List" title=" List " border="0"></label>
<input class="listing" id="Grid" style="visibility: hidden;" name="listing" onclick="hideForm()" type="radio">
<label class="listing" for="Grid">
<img src="/devsite/images/icons/table.png" alt="Grid" title=" Grid " border="0"> </label>
</div>
<div id="formdiv" style="display: block;"> some stuff </div>
<div id="formdiv2" style="display: block;"> some different stuff </div>
The javascript :
<script language="javascript">
function hideForm(){
if (document.getElementById('List').checked==true){
document.getElementById('formdiv').style.display="block";
document.getElementById('formdiv2').style.display="none";
} else {
document.getElementById('formdiv').style.display="none";
document.getElementById('formdiv2').style.display="block";
};
if (document.getElementById('Grid').checked==true){
document.getElementById('formdiv').style.display="none";
document.getElementById('formdiv2').style.display="block";
} else {
document.getElementById('formdiv').style.display="block";
document.getElementById('formdiv2').style.display="none";
};
}
</script>
What I need is a roll over cursor change, and background color change on selected radio buttons...the hide/show visible are working fine
For background color change you can use this:
YourElement.style.background = "#000000"
For cursor change:
YourElement.style.cursor = "type"
For different types of the cursor: cursor types doc
To display a cursor on hover try the following css:
img:hover {
cursor:pointer;
}
For the background, using jquery you can do the following:
$("#elementid").css("background", "#000000")
I have changed the radio code to :
<span style="float:right; margin:-10px 100px 0px 20px;">Change view: </span>
<input class="listing" id="List" style="visibility: hidden;" name="listing" onclick="hideForm()" type="radio">
<label class="List" for="List">
<img src="/devsite/images/icons/row.png" alt="List" title=" List " border="0"></label>
<input class="listing" id="Grid" style="visibility: hidden;" name="listing" onclick="hideForm()" type="radio">
<label class="Grid" for="Grid">
<img src="/devsite/images/icons/table.png" alt="Grid" title=" Grid " border="0"> </label>
</span>
and the javascript to:
<script language="javascript">
function hideForm(){
if (document.getElementById('List').checked==true){
document.getElementById('formdiv').style.display="block";
document.getElementById('formdiv2').style.display="none";
List.style.background = "#FFFFFF";
Grid.style.background = "#111111";
List.style.cursor = "pointer";
Grid.style.cursor = "pointer";
} else {
document.getElementById('formdiv').style.display="none";
document.getElementById('formdiv2').style.display="block";
List.style.background = "#111111";
Grid.style.background = "#FFFFFF";
List.style.cursor = "pointer";
Grid.style.cursor = "pointer";
};
if (document.getElementById('Grid').checked==true){
document.getElementById('formdiv').style.display="none";
document.getElementById('formdiv2').style.display="block";
List.style.background = "#111111";
Grid.style.background = "#FFFFFF";
List.style.cursor = "pointer";
Grid.style.cursor = "pointer";
} else {
document.getElementById('formdiv').style.display="block";
document.getElementById('formdiv2').style.display="none";
List.style.background = "#FFFFFF";
Grid.style.background = "#111111";
List.style.cursor = "pointer";
Grid.style.cursor = "pointer";
};
}
</script>
this is just getting messy.....

How to use multiple checkboxes to return a single div

I am working on a page with multiple checkboxes, and would like it to return a single div based on any combination of checks. I created a jsfiddle, but even though this is the code on my site that somewhat works, it is not working on jsfiddle:
HTML:
<div id="checkboxes">
<input type="checkbox" id="red" name="color">Red
<input type="checkbox" id="blue" name="color">Blue
<input type="checkbox" id="green" name="color">Green
</div>
<br /><br />
<div id="default" style="display:none;">Show this by default</div><br />
<div id="showred" style="display:none;">This is red</div><br />
<div id="showblue" style="display:none;">This is blue</div><br />
<div id="showgreen" style="display:none;">This is green</div><br />
<div id="showpurple" style="display:none;">This is purple</div>
JS:
$(document).ready(function() {
var r = $('#red');
var b = $('#blue');
var g = $('#green');
var p = r.add(b);
$(r).click(function(){
if ($(r).is(':not(:checked)')) {
$('#showred').show();
$('#showblue').hide();
$('#showgreen').hide();
$('#showpurple').hide();
$('#default').hide();
} else {
$('#showred').hide();
$('#showblue').hide();
$('#showgreen').hide();
$('#showpurple').hide();
$('#default').show();
}
});
$(b).click(function(){
if ($(b).is(':not(:checked)')) {
$('#showred').hide();
$('#showblue').show();
$('#showgreen').hide();
$('#showpurple').hide();
$('#default').hide();
} else {
$('#showred').hide();
$('#showblue').hide();
$('#showgreen').hide();
$('#showpurple').hide();
$('#default').show();
}
});
$(g).click(function(){
if ($(g).is(':not(:checked)')) {
$('#showred').hide();
$('#showblue').hide();
$('#showgreen').show();
$('#showpurple').hide();
$('#default').hide();
} else {
$('#showred').hide();
$('#showblue').hide();
$('#showgreen').hide();
$('#showpurple').hide();
$('#default').show();
}
});
$(p).click(function(){
if ($(r).is(':not(:checked)') && $(b).is(':not(:checked)')) {
$('#showred').hide();
$('#showblue').hide();
$('#showgreen').hide();
$('#showpurple').show();
$('#default').hide();
} else {
$('#showred').hide();
$('#showblue').hide();
$('#showgreen').hide();
$('#showpurple').hide();
$('#default').show();
}
});
});
http://jsfiddle.net/robert316/tu0o1z0s/13/
I would really appreciate any help to get this working correctly, what I would like to happen is:
User clicks "Red" -> Display red div
User clicks "Blue" -> Display blue div
User clicks "Red" and "Blue" -> Only display purple div (no red or blue)
I would also like to fix the behavior that when a user unchecks a box it reverts back to the default div display, ideally, if no boxes are selected it should show default div, and always display the div based on the combination of checkboxes.
Thank you very much for any help with this.
In case anyone finds this question, here is the final code I used to be able to show single divs from multiple checkbox selections:
Code Snippet:
$(document).ready(function () {
// select checkboxes by name
var packages = $("input[name='cc']");
// set main div id
var packageDiv = $("#listings");
// bind to change event
packages.change(function () {
// empty array
var idArr = [];
// get the checked values
var checked = $("input[name='cc']:checked");
// loop and build array
checked.each(function () {
idArr.push($(this).prop("id"));
});
// remove whitespace from multiple checkboxes array
var trimArray = idArr.join("");
toggleShowHide(trimArray, packageDiv);
});
});
function toggleShowHide(arr, elem) {
var arrLen = arr.length;
// clear last selection when unchecking boxes
$(".hide-me").hide();
// set default if array is empty
if (arrLen < 1 ){
setDefault(elem);
}
// run the show hide based on array of selection
for(i = 0; i < arrLen; i++) {
// set the name for the selected div
var temp = "#" + arr + "_div_id";
$(temp).show();
$("#default").hide();
}
// unhide
elem.show();
}
function setDefault(elem){
$("#default").show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- Checkbox -->
<input type="checkbox" id="i" name="cc" value="i_div_id" data-ref="i_div_id" />
<label>I</label>
<input type="checkbox" id="c" name="cc" value="c_div_id" data-ref="c_div_id" />
<label>C</label>
<input type="checkbox" id="p" name="cc" value="p_div_id" data-ref="p_div_id" />
<label>P</label>
<br />
<br />
<br />
<br />
<!-- Loaded/hidden content div-->
<div id="listings">
<div class="hide-me" id="default"><strong>This is default copy on page</strong></div>
<div class="hide-me" id="i_div_id" style="display:none;">You ordered: <strong>I Package</strong></div>
<div class="hide-me" id="c_div_id" style="display:none;">You ordered: <strong>C Package</strong></div>
<div class="hide-me" id="p_div_id" style="display:none;">You ordered: <strong>P Package</strong></div>
<div class="hide-me" id="ic_div_id" style="display:none;">You ordered: <strong>I-C Package</strong></div>
<div class="hide-me" id="ip_div_id" style="display:none;">You ordered: <strong>I-P Package</strong></div>
<div class="hide-me" id="cp_div_id" style="display:none;">You ordered: <strong>C-P Package</strong></div>
<div class="hide-me" id="icp_div_id" style="display:none;">You ordered: <strong>I-C-P Package</strong></div>
</div>
Rather than creating a color div for each color, why not use a single color-div and just change its css properties / classes? This would eliminate the need for extraneous show-hide / if-else logic when checkbox selections are made.
This snippet illustrates how you can "return a div based on any combination of checks" - it relies on css to handle setting the properties of a target div but you could very well handle all of this in jQuery as well.
Example:
$(document).ready(function() {
// checkboxes with name 'color', 'color-div', and reset button
var colors = $("input[name='color']");
var colorDiv = $("#color-div");
var reset = $("#reset");
// bind to 'colors' change event:
colors.change(function() {
// empty array to hold the color ids
var idArr = [];
// get the checked colors
var checked = $("input[name='color']:checked");
// loop and build array
checked.each(function() {
idArr.push($(this).prop("id"));
});
// function below
toggleColors(idArr, colorDiv);
});
// reset to defaults
$("#reset").click(function() {
// function below
setDefault(colorDiv);
// back to hidden
colorDiv.hide();
// uncheck the check boxes
$("input[name='color']:checked").removeAttr("checked");
});
});
/// function to add color css classes based on checkbox id array
function toggleColors(arr, elem) {
var arrLen = arr.length;
// set default if array is empty
if (arrLen < 1) {
setDefault(elem);
return;
};
// remove classes, add classes
elem.removeClass();
for (i = 0; i < arrLen; i++) {
elem.addClass(arr[i]);
}
// unhide
elem.show();
}
/// set the color div to "default"
function setDefault(elem) {
elem.removeClass();
elem.addClass("default");
}
/*
using css to handle color and content change!
this will prevent you from having to write complicated "if-else"
jQuery blocks.
*/
#color-div {
height: 100px;
width: 100px;
border: solid 2px #d3d3d3;
margin-bottom: 20px;
}
.default,
.default:after {
background-color: #fff;
content: "Please select a color";
}
.yellow,
.yellow:after {
background-color: yellow;
content: "I am Yellow!";
}
.red,
.red:after {
background-color: red;
content: "I am Red!";
}
.blue,
.blue:after {
background-color: blue;
content: "I am Blue!";
}
.yellow.blue,
.yellow.blue:after {
background-color: green;
content: "I am Green!";
}
.yellow.red,
.yellow.red:after {
background-color: orange;
content: "I am Orange!";
}
.blue.red,
.blue.red:after {
background-color: purple;
content: "I am Purple!";
}
.blue.red.yellow,
.blue.red.yellow:after {
background-color: brown;
content: "I am Brown :(";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="checkboxes">
<input type="checkbox" id="red" name="color" />
<label>Red</label>
<input type="checkbox" id="blue" name="color" />
<label>Blue</label>
<input type="checkbox" id="yellow" name="color" />
<label>Yellow</label>
</div>
<br />
<br />
<div id="color-div" style="display:none;"></div>
<button id="reset">Reset</button>
If css classes isn't your bag, you could essentially handle the same "toggling" through building an equivalent javascript object.
[Edit - Using a Div for Each Checkbox]
Since you have control over the properties of the checkboxes, you should use one of these properties to tie to the element being loaded by your query. You should also try to avoid using id for more than one element. For example if you have this:
<!-- Checkbox -->
<input type="checkbox" id="burgers" name="color" />
<!-- Loaded/hidden content div-->
<div id="burgerDiv" style="display:none;"></div>
I would suggest adding to your checkbox either a data-* or value attribute that ties to the id of the hidden div. I'm not sure how well the data attribute is supported in all browsers, however. Example:
<!-- Checkbox -->
<input type="checkbox" id="burgers" name="color" value="burgersDiv" data-ref="burgersDiv" />
... Then it's pretty easy to hide/show the div:
fiddle

Categories

Resources