Change class bg if checkbox is checked - javascript

I'm working on my portfolio website and need some help with a bit jQuery code. I want a parent class to react to the checkbox in it. In this case, the background color needs to change to #000 when the checkbox is active/checked.
I don't know what line of code to add to make my class react to the checkbox. I've searched on google on how to do it but didn't get much wiser. It's probably a really small thing but I would hope to get some help from you guys.
$("input[type='checkbox']").change(function() {
if ($(this).is(":checked")) {
$(this).parent();
} else {
$(this).parent();
}
});
.product {
background-color: #ccc;
/* needs to change to #000 when active */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="product">
<input class="check" type="checkbox" name="logo"> Logo
</div>

Basically you create a second (more specific) css selector for the active state, then you use your jQuery to toggle that state/class based on the checkbox value.
https://jsbin.com/betafupogu/1/edit?html,css,js,output
CSS
.product {
background-color: #ccc; /* needs to change to #000 when active */
}
.product.active {
background-color: #000;
}
jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("input[type='checkbox']").change(function(){
if($(this).is(":checked")){
$(this).parent().addClass('active');
}else{
$(this).parent().removeClass('active');
}
});
</script>

Related

Hide and show an item based on a toggled is-active class

I used the following code to toggle a button class in order to make a full-screen mobile menu.
HTML
button class="hamburger hamburger--slider" type="button">
<a href='#'><div class="hamburger-box">
<div class="hamburger-inner"></div>
</div>
</a>
document.addEventListener('DOMContentLoaded', function() {
jQuery(function($){
$('.hamburger').click(function(){
$('.hamburger--slider').toggleClass('is-active');
});
});
});
Now I would like to hide another item in my header when the toggled class .is-active is present.
The following code works to hide the item, but once the toggled class is gone, the item does not reappear but stays hidden until the page is reloaded.
jQuery(function($) {
if ($('.hamburger--slider.is-active').length) {
$('.rey-headerCart-wrapper').hide();
}
});
Appreciate any help :) !
you have to show the element again after the burger menu closes:
document.addEventListener('DOMContentLoaded', function() {
jQuery(function($){
$('.hamburger').click(function(){
$('.hamburger--slider').toggleClass('is-active');
// hide / show other element
if ($('.hamburger--slider.is-active').length) {
$('.rey-headerCart-wrapper').hide();
} else {
$('.rey-headerCart-wrapper').show();
}
});
});
});
Or in vanilla javascript:
window.addEventListener("load", () => {
document.querySelector(".hamburger").addEventListener("click", () => {
document.querySelector(".hamburger--slider").classList.toggle("is-active");
// hide / show other element
const cart = document.querySelector(".rey-headerCart-wrapper");
if (document.querySelector(".hamburger--slider.is-active")) {
cart.style.display = "none";
} else {
cart.style.display = "block";
// apply original display style
// cart.style.display = "inline-block";
// cart.style.display = "flex";
};
});
})
In order to make toggle functions like this more understandable, maintainable and extendable you need to think about your HTML structure.
In your current structure, you have a button that toggles a class on itself. Therefore any element beyond that button that has to change appearance or beaviour has to check which class that button has, or you have to extend the click-event handler in order to add these elements (that's what you did here).
This can get quite messy really fast.
A better approach could be to not toggle a class on the button but on an element that is a common parent to all elements that you want to change the behavior of.
That way anything you ever add to that wrapper already can be manipulated via CSS, without the need of changing your JS.
$('.nav-toggler').on('click', function() {
$('#nav-wrapper').toggleClass('active');
});
.menu, .cart {
padding: 1em;
margin: 2px;
}
.cart {
background: #FFF000;
}
.menu{
background: #F1F1F1;
display: none;
}
#nav-wrapper.active > .menu {
display: block;
}
#nav-wrapper.active > .cart {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="nav-wrapper">
<button class="nav-toggler">Toggle</button>
<div class="menu">My Menu</div>
<div class="cart">My Cart</div>
</div>

Add & remove classes with fewer lines of code

I'm trying to learn how to shorten my jQuery code. Any suggestions or tips would be awesome:
jQuery(document).ready(function($){
$('#checkout_timeline #timeline-4').click(function() {
if ($('#checkout_timeline #timeline-4').hasClass('active')) {
$('#checkout-payment-container').addClass('cpc-visible');
}
});
$('#checkout_timeline #timeline-1, #checkout_timeline #timeline-2, #checkout_timeline #timeline-3').click(function() {
$('#checkout-payment-container').removeClass('cpc-visible');
});
});
To avoid clutter, please find the working version here:
My JSFiddle Code
I know I can use .show() and .hide() but due to other CSS considerations I want to apply .cpc-visible.
There are a handful of things you can improve here. First, you're over-specifying. Ids are unique. No need to select #checkout_timeline #timeline-4 when just #timeline-4 will do. But why even have ids for each li? You can reference them by number using the :nth-child(n) selector. Or better yet, you've already given them application-specific class names like billing, shipment, and payment. Use those! Let's simplify the original content to:
<ul id="checkout_timeline">
<li class='billing'>Billing</li>
<li class='shipping'>Shipping</li>
<li class='confirm'>Confirm</li>
<li class='payment active'>Payment</li>
</ul>
<div id='checkout-payment-container' class='cpc-visible'>
This is the container to show and hide.
</div>
Notice I left the active class, and indeed further initialized the checkout
div with cpc-visible to mirror the payment-is-active condition. Usually I would keep HTML as simple as possible and put "starting positions" initialization in code. But "in for a penny, in for a pound." If we start with payment active, might as well see that decision through, and start the dependent div in a consistent state.
Now, revised JavaScript:
jQuery(document).ready(function($) {
$('#checkout_timeline li').click(function() {
// make clicked pane active, and the others not
$('#checkout_timeline li').removeClass('active');
$(this).addClass('active');
// show payment container only if payment pane active
var paymentActive = $(this).hasClass('payment');
$('#checkout-payment-container').toggleClass('cpc-visible', paymentActive);
});
});
This code is much less item-specific. It doesn't try to add separate click handlers for different tabs/panes. They all get the same handler, which makes a uniform set of decisions. First, that whichever pane is clicked, make it active and the others not active. It does this by removing all active classes, then putting active on just the currently selected pane. Second, it asks "is the current pane the payment pane?" And it uses the toggleClass API to set the cpc-visible class accordingly. Often such "set class based on a boolean condition" logic is simpler and more reliable than trying to pair appropriate addClass and removeClass calls.
And we're done. Here's a JSFiddle that shows this in action.
Try this : You can user jquery selector with timeline and active class to bind click event handler where you can add required class. Same selector but not having active class to remove class.
This will be useful when you add / remove elements and will be more flexible.
jQuery(document).ready(function($){
$('#checkout_timeline .timeline.active').click(function() {
$('#checkout-payment-container').addClass('cpc-visible');
});
$('#checkout_timeline .timeline:not(.active)').click(function() {
$('#checkout-payment-container').removeClass('cpc-visible');
});
});
JSFIddle
Here is one of the ways, you can shorten this code by using :not(). Also its better to use elements than to reference and get them via JQuery always.
jQuery(document).ready(function($) {
var showHideContainer = $('#checkout-payment-container');
$('#checkout_timeline .timeline.active').click(function() {
showHideContainer.addClass('cpc-visible');
});
$('#checkout_timeline .timeline:not(.payment)').click(function() {
showHideContainer.removeClass('cpc-visible');
});
});
try this code its working fine with fiddle
$('.timeline').click(function() {
if ($(this).hasClass('active') && $(this).attr("id") == "timeline-4")
$('#checkout-payment-container').addClass('cpc-visible');
else
$('#checkout-payment-container').removeClass('cpc-visible');
});
This would of been my approach cause you still have to add/remove the active class between each li.
jQuery(document).ready(function($) {
$('ul li').click(function() {
$('ul li.active').removeClass('active');
$(this).closest('li').addClass('active');
k();
});
var k = (function() {
return $('#timeline-4').hasClass('active') ? $('#checkout-payment-container').addClass('cpc-visible') : $('#checkout-payment-container').removeClass('cpc-visible');
});
});
#checkout-payment-container {
float: left;
display: none;
background: red;
color: white;
height: 300px;
width: 305px;
padding: 5px;
}
ul {
list-style: none;
width: 100%;
padding: 0 0 20px 0px;
}
li {
float: left;
padding: 5px 11px;
margin-right: 5px;
background: gray;
color: white;
cursor: pointer;
}
li.active {
background: black;
}
.cpc-visible {
display: block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="checkout_timeline">
<li id='timeline-1' class='timeline billing'>Billing</li>
<li id='timeline-2' class='timeline shipping'>Shipping</li>
<li id='timeline-3' class='timeline confirm'>Confirm</li>
<li id='timeline-4' class='timeline payment'>Payment</li>
</ul>
<div id='checkout-payment-container'>
This is the container to show and hide.
</div>
Your code look great, i would have written it the same.
bit sure how much it helps but if you like, you can use inline if like this:
$(document).ready(function(){
$('#B').click(function() { (!$('#B').hasClass('active')) ?
$('#A').addClass('active') : ''; });
$('#C').click(function() { $('#A').removeClass('active'); });
});
Link for a live example:
jsFiddle

JQuery - Disable submit button unless original form data has changed

I found the following code here (Disable submit button unless original form data has changed) and it works but for the life of me, I can't figure out how to change the properties, text and CSS of the same submit button.
I want the text, background and hover background to be different when the button is enabled/disabled and also toggle another DIV visible/hidden.
$('form')
.each(function(){
$(this).data('serialized', $(this).serialize())
})
.on('change input', function(){
$(this)
.find('input:submit, button:submit')
.prop('disabled', $(this).serialize() == $(this).data('serialized'))
;
})
.find('input:submit, button:submit')
.prop('disabled', true);
Can someone please provide a sample. I have no hair left to pull out :-)
The answer you've copied isn't that great because a form doesn't have change or input events. Form elements do, instead. Therefore, bind the events on the actual elements within the form. Everything else looks okay except that you need to store the state of whether or not the stored/current data is equal to each other and then act accordingly. Take a look at the demo that hides/shows a div based on the state.
$('form')
.each(function() {
$(this).data('serialized', $(this).serialize())
})
.on('change input', 'input, select, textarea', function(e) {
var $form = $(this).closest("form");
var state = $form.serialize() === $form.data('serialized');
$form.find('input:submit, button:submit').prop('disabled', state);
//Do stuff when button is DISABLED
if (state) {
$("#demo").css({'display': 'none'});
} else {
//Do stuff when button is enabled
$("#demo").css({'display': 'block'});
}
//OR use shorthand as below
//$("#demo").toggle(!state);
})
.find('input:submit, button:submit')
.prop('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input name="tb1" type="text" value="tbox" />
<input name="tb2" type="text" value="tbox22" />
<input type="submit" value="Submit" />
</form>
<div id="demo" style="margin-top: 20px; height: 100px; width: 200px; background: red; display: none;">Data isn't the same as before!</div>
And the rest could be done via CSS using the :disabled selector(CSS3) or whatever is appropriate.
You can change the hover style of the button using css. CSS has hover state to target:
[type='submit']:disabled {
color: #ddd;
}
[type='submit']:disabled:hover {
background-color: grey;
color: black;
cursor: pointer;
border: none;
border-radius: 3px;
}
[type='submit']:disabled {
color: #ccc;
}
For showing and hiding, there are many tricks to do it. I think following would be the simplest trick to do and and easier for you to understand.
Add this in your html
<div id="ru" class="hide">this is russia</div>
<div id="il" class="hide">this is israel</div>
<div id="us" class="hide">this is us</div>
<div id="in" class="hide">this is india</div>
Add this in your css
.hide {
display: none;
background: red;;
}
Update your javascript like following:
$('form').bind('change keyup', function () {
.....
// get id of selected option
var id = $("#country-list").find(":selected").val();
$('.hide').hide(); // first hide all of the divs
$('#' + id).show(); // then only show the selected one
....
});
Here is the working jsfiddle. Let me know if this is not what you are looking for and I will update the answer.
The detection of change occurs on change input event.
You can change your code to the following in order to use this calculated value:
$('form')
.each(function(){
$(this).data('serialized', $(this).serialize())
})
.on('change input', function(){
var changed = $(this).serialize() != $(this).data('serialized');
$(this).find('input:submit, button:submit').prop('disabled', !changed);
// do anything with your changed
})
.find('input:submit, button:submit')
.prop('disabled', true)
It is good if you want to work with other divs. However, for styling, it is better to use CSS :disabled selector:
For example, in your CSS file:
[type='submit']:disabled {
color: #DDDDDD;
}
[type='submit']:disabled {
color: #CCCCCC;
}

How to remove and add class with if statement?

I am trying to have the classes change depending on what is clicked from the two headings.
If heading one is clicked, I want the font color to change to red and have it underlined with red, which in the class it currently does with a bottom border. If the other heading is clicked then I want that heading to take on the red characteristics. The one that is not clicked will just stay grey according to the no highlight class.
Here is the JSFiddle: http://jsfiddle.net/7ok991am/1/ I give an example look also of what I am trying to accomplish.
HTML:
<div id="page_headings">
<h2 class="no_highlight">Heading One</h2>
<h2 class="no_highlight">Heading Two</h2>
</div>
CSS:
#page_headings{
overflow: hidden;
margin-bottom: 32px;
}
#page_headings h2{
float: left;
margin-right:24px;
font-size: 14px;
cursor:pointer;
}
#page_headings h2:hover{
font-weight: bold;
}
.red_highlight{
color:red;
border-bottom: 1px solid red;
}
.no_highlight{
color:#898989;
}
JS:
$('#page_headings').on('click', function(){
if($('#page_headings h2').hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$('#page_headings h2').addClass('no_highlight');
};
});
Building on #RDrazard I think you want them to switch between the two correct?
http://jsfiddle.net/7ok991am/3/
$('#page_headings h2').on('click', function(){
if($(this).hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$(this).addClass('no_highlight');
}
$(this).siblings('h2').addClass('no_highlight');
});
JSFiddle: Link
First off, add a border-bottom property with none to the no highlight class to ensure that it looks just the same before the click.
Next, you want to the click event associated with the h2 elements, so it should be $('#page_headings h2')
Use this to impact the h2 we're clicking on.
Try this code
$('#page_headings h2').on('click', function(){
if($(this).hasClass('no_highlight')){
$(this).removeClass('no_highlight').addClass('red_highlight');
}else{
$(this).addClass('no_highlight').removeClass('red_highlight');
}
});
Check this fiddle
JS
$('.no_highlight').on('click', function(){
$(this).parent().find('.no_highlight').css('border-bottom','none');
$(this).css('border-bottom','1px solid red');
});
The above method changes the border of the currently clicked headinh which i think is what you want.
AND
if you want addClass() and removeClass(), then see this fiddle
JS
$('.no_highlight').on('click', function(){
$(this).parent().find('.no_highlight').removeClass('red_highlight');
$(this).addClass('red_highlight');
});
This method adds a red_highlight class to the active link and removes the red_highlight when not active.
Please try it..

jQuery conditional add and remove CSS property

I have a CSS border property in place currently (border-left: 1px), and onClick, I have it removed via the first jQuery function below.
How can I set this up so that my second function will add back the property upon the second click? It should switch back and forth per click.
$(function(){
$('#button').click(function() {
$('#button-2').css('border-left','none');
});
$('#button').click(function() {
$('#button-2').css('border-left','1px');
});
});
I have now included the original code: www.jsfiddle.net/tonynggg/frnYf/12
Would it be easier to define a css class:
.button { border-left: 1px; }
.buttonClicked { border-left: none; }
And then use the jQuery toggleClass
So your code would be:
$(function(){
$('#button').click(function() {
$('#button-2').toggleClass('buttonClicked');
});
});
That would then toggle your alternate css class on an off when it's clicked. If nothing else, this should get you pointed in the right direction.
First, create a class that has the border:
.borderclass
{
border-left:1px black solid;
}
And then,
$(function(){
$('#button').click(function() {
if ($('#button-2').hasClass('borderclass'))
$('#button-2').removeClass('borderclass');
else
$('#button-2').addClass('borderclass');
});
});

Categories

Resources