Why does my jQuery toggle workaround not work? - javascript

Since I couldn't make it work with the jQuery toggle function I try to build a workaround which doesn't work as well. If I just go for removeClass onClick, it removes the class. But both the toggle and if..else logic won't work.
Where's my bug?
$('.category-wrapper').click(function() {
if ($(this).hasClass("category-deselected")) {
$(this).removeClass("category-deselected")
} else {
$(this).addClass("category-deselected")
}
});
.category-deselected {
color: red;
}
.category-wrapper input {
position: fixed;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="category-wrapper category-deselected"><label for="id_poller_category_17"><input type="radio" name="poller_category" value="17" class="poller-category-radio" id="id_poller_category_17" required="">
click me to change color</label></div>

Your code looks Excellent !! you just need to prevent the bubble effect which causes trigger the handler 2 times , you can see more here bubble events
e.preventDefault()
$('.category-wrapper').click(function(e) {
if ($(this).hasClass("category-deselected")) {
$(this).removeClass("category-deselected")
} else {
$(this).addClass("category-deselected")
}
e.preventDefault(); // <-- this line your solution
});
.category-deselected {
color: red;
}
.category-wrapper input {
position: fixed;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="category-wrapper category-deselected"><label for="id_poller_category_17"><input type="radio" name="poller_category" value="17" class="poller-category-radio" id="id_poller_category_17" required="">
click me to change color</label></div>

you can easily toggle a checkbox but you can't toggle a radio cause it checked just once. if you are planning to use multiple radios instead then you can use the following link: JSFiddle click to test the example.
// Multiple Radio Color Change Example:
JSFiddle
// Radio Example:
$(document).ready(function() {
$('#radio-example input:radio').change(function() {
$("label").toggleClass("category-deselected");
});
});
.category-deselected {
color: red;
}
.category-wrapper input {
position: fixed;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="radio-example" class="category-wrapper">
<div class="row">
<label for="id_poller_category_17">click me to change color</label>
<input type="radio" name="poller_category" value="17" class="poller-category-radio" id="id_poller_category_17"> </div>
</div>
//Checkbox Example:
$(document).ready(function() {
$('#radio-example input:checkbox').change(function() {
$("label").toggleClass("category-deselected");
});
});
.category-deselected {
color: red;
}
.category-wrapper input {
position: fixed;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="radio-example" class="category-wrapper">
<div class="row">
<label for="id_poller_category_17">click me to change color</label>
<input type="checkbox" name="poller_category" value="17" class="poller-category-radio" id="id_poller_category_17"> </div>
</div>

The issue is that you have both a <label> and an <input> in your div, and the they both send a click event, which results in your function executing twice, nearly simultaneously. You can get around this by ignoring the click on the label:
$('.category-wrapper').click(function() {
if (event.target.nodeName !== "LABEL") {
if ($(this).hasClass("category-deselected")) {
$(this).removeClass("category-deselected")
} else {
$(this).addClass("category-deselected")
}
}
});
.category-deselected {
color: red;
}
.category-wrapper input {
position: fixed;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="category-wrapper category-deselected"><label for="id_poller_category_17"><input type="radio" name="poller_category" value="17" class="poller-category-radio" id="id_poller_category_17" required="">
click me to change color</label></div>

$('.category-wrapper').click(function() {
if ($(this).hasClass("category-deselected")) {
$(this).removeClass("category-deselected")
} else {
$(this).addClass("category-deselected")
}
});
Think about your logic ... if hasClass ( remove class) ... else ( addClass )
Your script first check if $(this) hasClass and then remove it ... and then make "else" and addClass

Related

Changing input button to images

I am new to JavaScript.
I am having trouble changing the show button and hide button to images instead.
The show button will be a different image to the hide button.
How would I go about doing this?
https://jsfiddle.net/ej0r4amd/2/
$(document).ready(function() {
$("#button").on("click", function() {
$("#collapse").slideToggle("slow");
if ($(this).val() == "Hide")
$(this).val("Show");
else
$(this).val("Hide");
});
});
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<input type="button" value="Hide" id="button">
<div id="collapse">
Hello World
</div>
Since you're using jQuery, you can use the <input type="image"> and change the src attribute using .attr("src".
$(document).ready(function() {
$("#button").on("click", function() {
$("#collapse").slideToggle("slow");
if ($(this).val() == "Hide") {
$(this).val("Show");
$(this).attr("src","https://www.gravatar.com/avatar/2e83e2d35f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
} else {
$(this).val("Hide");
$(this).attr("src","https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="image" value="Hide" id="button" src="https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1"></button>
<div id="collapse">
Hello World
</div>
There are a few ways to do what you want.
You could use an img tag and onClick change the src value
You could use an element ( eg span ) and on click change backgroundImage property.
Or, like in the example below, use an element and on click toggle the className and in css add different background-image for each className
$(document).ready(function() {
$(".trigger").on("click", function() {
$("#collapse").slideToggle("slow");
$(this).toggleClass('show', 'hide')
});
});
.trigger {
width: 50px;
height: 50px;
display: inline-block;
background-repeat: no-repeat;
background-size: cover;
background-position: center center;
}
.hide {
background-image: url("https://via.placeholder.com/50x50")
}
.show {
background-image: url("https://via.placeholder.com/100x100")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="trigger hide"></span>
<div id="collapse">
Hello World
</div>
I would just add a class, and then control the background image of the button with a class—in this case: .show.
You had forgotten a quotation mark on type="button".
$(document).ready(function() {
$("#button").on("click", function() {
$("#collapse").slideToggle("slow");
if ($(this).val() == "Hide") {
$(this).val("Show");
$(this).toggleClass("show");
} else {
$(this).val("Hide");
$(this).toggleClass("show");
}
});
});
#button {
color: white;
background-image: url("https://picsum.photos/id/1/50/50");
}
#button.show {
background-image: url("https://picsum.photos/id/20/50/50");
color: black;
}
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<input type="button" value="Hide" id="button">
<div id="collapse">
Hello World
</div>

How to change button color when radio input is selected, but input is wrapped in div before label?

I am trying to make our dinky radio buttons into lovely toggle buttons on our donation page. The HTML cannot be modified, and as it stands the inputs are wrapped in divs, then followed by the labels. I have zero knowledge of JS/jQuery and I imagine this task requires some.
Here is my fiddle: https://jsfiddle.net/cgz63qhd/
body {
padding: 10px;
font-family: sans-serif;
}
div.donation-levels {
margin: 3px 0;
}
.donation-level-container {
display: inline-block;
}
.donation-level-container input {
visibility: hidden;
}
.donation-level-amount-container {
text-align: center;
margin: 5px 2px;
padding: 0.7em 2em;
color: #ffffff;
background-color: #1a92b4;
border-radius: 5px;
display: inline-block;
cursor: pointer;
font-size: 22px;
}
.donation-level-amount-container:hover {
background: #e8525f;
color: #ffffff;
}
.donation-level-label-input-container input:checked~label {
background: #e8525f;
}
<div class="donation-level-container">
<div class="form-content">
<div class="donation-level-input-container form-input">
<div class="donation-level-label-input-container">
<input name="level_flexibleexpanded" id="level_flexibleexpanded5942" value="5942" onclick="evalMatchingGift('$35.00');" type="radio">
</div>
<label for="level_flexibleexpanded5942" onclick="">
<div class="donation-level-amount-container">
$35.00
</div>
</label>
</div>
<input name="level_flexibleexpandedsubmit" id="level_flexible_5942expandedsubmit" value="true" type="hidden">
</div>
</div>
<div class="donation-level-container">
<div class="form-content">
<div class="donation-level-input-container form-input">
<div class="donation-level-label-input-container">
<input name="level_flexibleexpanded" id="level_flexibleexpanded5943" value="5943" onclick="evalMatchingGift('$60.00');" type="radio">
</div>
<label for="level_flexibleexpanded5943" onclick="">
<div class="donation-level-amount-container">
$60.00
</div>
</label>
</div>
<input name="level_flexibleexpandedsubmit" id="level_flexible_5943expandedsubmit" value="true" type="hidden">
</div>
</div>
<div class="donation-level-container">
<div class="form-content">
<div class="donation-level-input-container form-input">
<div class="donation-level-label-input-container">
<input name="level_flexibleexpanded" id="level_flexibleexpanded5944" value="5944" onclick="evalMatchingGift('$120.00');" type="radio">
</div>
<label for="level_flexibleexpanded5944" onclick="">
<div class="donation-level-amount-container">
$120.00
</div>
</label>
</div>
<input name="level_flexibleexpandedsubmit" id="level_flexible_5944expandedsubmit" value="true" type="hidden">
</div>
</div>
Here is my inspiration donate page: https://action.audubon.org/donate/now
Alas, their labels are set up better so I think they were able to make the buttons with pure CSS (?).
My buttons currently are looking decent, are sized fine and colored nicely, but they just won't stay that coral color when clicked! Can someone help me out?
I've seen a lot of questions here on this topic but I can't seem to get anything to work.
I'm sure there are other issues in the code, please point them out if you see them!
$(".donation-level-amount-container").on("click", function() {
$('.donation-level-amount-container').each(function() {
$(this).removeClass('active');
});
$(this).toggleClass('active');
})
And css
.active {
background:#e8525f;
color:#ffffff;
}
Working fiddle:
https://jsfiddle.net/29exoa4k/2/
You need this piece of jQuery:
$(function() {
$(document).on('click','.donation-level-amount-container',function(){
$('.donation-level-amount-container').removeClass('active');
$(this).addClass('active');
});
});
Update also to this CSS:
.donation-level-amount-container:hover, .donation-level-amount-container.active {
background:#e8525f;
color:#ffffff;
}
Here is the updated jsfiddle.
You want something like this
$(".donation-level-amount-container").on("click", function() {
$(this).css("background", "red");
})
or to toggle an active class
$(".donation-level-amount-container").on("click", function() {
$(this).toggleClass("active");
})
You need this
$(".donation-level-amount-container").on("click", function() {
$(".donation-level-amount-container").css("background", "#1a92b4");
$(this).css("background", "#e8525f");
})
and css !important for background property
.donation-level-amount-container:hover {
background:#e8525f!important;
color:#ffffff;
}
here's your updated fiddle https://jsfiddle.net/cgz63qhd/3/
Indeed, this can not be done with pure CSS, since you can't traverse upward in the DOM using CSS selectors. As previous answers mentioned, it can easily be done with jQuery, but it can also be done in vanilla javascript.
var donationButtons = document.querySelectorAll('.donation-level-amount-container');
var defaultBg = '#1a92b4';
var activeBg = '#f00';
donationButtons.forEach(function(btn){
btn.onclick = function(){
donationButtons.forEach(function(btn){
// deselect previously selected buttons
btn.style.background = defaultBg;
});
this.style.background = activeBg;
}
});
I'm certain this can be done smoother, but this is the first solution that popped up in my head.

how to add a class to an element when i click a different element with jquery

I have an input that is supposed to add a class of clicked to another element with an id of #zip when clicked. Here is the code:
$('#billing_zip').click(function () {
$('#zip').addClass('clicked');
});
#zip {
color: #444;
font-style: italic;
position: absolute;
top: 8px;
left: 35px
}
.clicked {
display: none;
}
<div class="chkField">
<label for="billing_zip">Zip</label>
<input type="text" onchange="clearContent(this);check_address('billing');" class="txtBoxStyle hasPlaceholder" tabindex="10" size="10" value="" id="billing_zip" maxlength="15" name="billing_zip">
<!--START: req_billing_zip-->
<img width="12" height="12" alt="" src="assets/templates/common/images/error2.gif">
<!--END: req_billing_zip-->
<div class="clear"></div>
<div id="zip">zip</div>
</div>
I don't know why the above jQuery is not working.
You forgot to declare id for billing_zip.
$(document).ready(function(){
$('#billing_zip').click(function () {
alert('hi');
$('#zip').addClass('clicked');
});
});
#zip {
color: #444;
font-style: italic;
position: absolute;
top: 8px;
left: 35px
}
.clicked {
display: none;
}
<div class="chkField">
<label id="billing_zip" for="billing_zip">Zip</label>
<input type="text" onchange="clearContent(this);check_address('billing');" class="txtBoxStyle hasPlaceholder" tabindex="10" size="10" value="" id="billing_zip" maxlength="15" name="billing_zip">
<!--START: req_billing_zip-->
<img width="12" height="12" alt="" src="assets/templates/common/images/error2.gif">
<!--END: req_billing_zip-->
<div class="clear"></div>
<div id="zip">zip</div>
</div>
Check out the jsfiddle here. Use document.ready if required. One important point i found out is that, if the placeholder text on input box is lengthy, then it covers up entire input box area and doesn't allow to trigger click event. refer the jsfiddle.
$('#billing_zip').click(function () {
$('#zip').addClass('clicked');
});
$('#zip').click(function () {
$('#zip').addClass('clicked');
});
Your code is working OK
It could be 2 possible issues:
You are missing to add the jQuery reference:
You should wrap your code inside the document.ready event:
$(function(){
$('#billing_zip').click(function () {
$('#zip').addClass('clicked');
});
});
If this only what you want. Then you can do directly like:
$('#billing_zip').click(function () {
$('#zip').css("display","none"); // or you can use hide or fadeout property.
});
When I wrapped your jQuery code in a "$(document).ready" it worked:
$(document).ready(function(){
$('#billing_zip').click(function () {
$('#zip').addClass('clicked');
});
});

stopImmediatePropagation() of sibling not working

I show a search field on some text click, and hide it on search input blur.
But if I click on the search button I don’t want to hide the input field, and prevent it from being hidden (because of the blur). I tried to stopImmediatePropagation() without any luck.
Here’s some code:
// Not working. when search button is pressed, disable hiding the search input
$('.search-contacts-container > button').on('click touchstart', function(e) {
alert('xxx');
e.stopImmediatePropagation();
})
// when search input is blurred, hide it
$('#search-contacts').on('blur', function() {
$('.search-contacts-container').addClass('visuallyhidden');
$('#search-contacts').attr('required', 'false').blur();
})
// when search input is focused, show it
$('#search-contacts').on('focus', function() {
$('.search-contacts-container').removeClass('visuallyhidden');
$('#search-contacts').attr('required', 'true');
})
// on search text click, show the search input
$('.js-show-search').on('click touchstart', function() {
if ($('.search-contacts-container').is('.visuallyhidden')) {
$('.search-contacts-container').removeClass('visuallyhidden');
$('#search-contacts').attr('required', 'true').focus();
} else {
$('.search-contacts-container').addClass('visuallyhidden');
$('#search-contacts').attr('required', 'false').blur();
}
})
HTML:
<span class="js-show-search" title="Search for contacts">Search</span>
<form action="search" method="post" class="form-search search-contacts-container visuallyhidden">
<input type="text" id="search-contacts" placeholder="Search" required="false" />
<button type="submit" class="form-search__button" title="Search"></button>
</form>
Demo: http://jsfiddle.net/un775/
Any ideas?
Check out my new JsFiddle. I use this method on day to day tasks. I hope it helps you.
Basically what you are doing is adding a background that masks everything behind it, and then adding a click even listener to it that hides everything. The form/input is in front of the background allowing you to interact with it.
HTML
<div id="js-show-search">...</div>
<form id="search-contacts" class="hide">...</form>
<div id="background" class="hide"></div>
JavaScript
var searchContact, background;
searchContact = $('#search-contacts');
background = $('#background');
$('#js-show-search').on('click', function(){
//remove .hide to show elements
});
$('#background.close').on('click', function(){
//add .hide to hide elements
});
CSS
html, body {
height: 100%;
}
#background {
height: 100%;
width: 100%;
position: absolute;
top:0;
left: 0;
z-index: 0;
}
#search-contacts {
position: relative;
z-index: 1;
display: inline-block;
}
.hide {
display: none!important;
}
http://jsfiddle.net/un775/7/

Having trouble with jQuery "on" click

I am trying to fire a function from either radio button when they are clicked but it doesn't seem to be working.
My code:
$('.radio [name=list_in]').on('click', function() {
updateListingForm('list_in');
});
My HTML:
<div class="fields">
<div class="radio">
<div class="pretty_rb styledRadio" style="background-image: url('images/form-radio-icons.png'); width: 19px; height: 20px; cursor: pointer; background-position: 0px -20px;"><input type="radio" checked="" value="auction" class="pretty_rb" id="list_site" name="list_in" style="display: none;"></div><label for="list_site">Site</label>
</div>
<div class="radio">
<div class="pretty_rb styledRadio" style="background-image: url('images/form-radio-icons.png'); width: 19px; height: 20px; cursor: pointer; background-position: 0px 0px;"><input type="radio" value="store" class="pretty_rb" id="list_store" name="list_in" style="display: none;"></div><label for="list_store">Store</label>
</div>
<div class="contentClear"></div>
</div>
I am using a jQuery plugin to style the radio fields and this is the HTML it outputs, so that is why the normal radio fields are hidden.
I can't use the onclick event because of this reason; that's why I tried using the on here but I can't seem to get it to fire?
What am I doing wrong!?
Assign the listener to the rendered elements instead of the hidden ones:
$('.radio .pretty_rb').on('click', function() {
updateListingForm('list_in');
});
Try this,
$('.radio').on('click', function() {
updateListingForm('list_in');
});
I guess you miss a $(document).ready(function() {...});
This code works for me:
$(document).ready(function() {
$('.radio [name=list_in]').on('click', function() {
alert('It works');
});
});

Categories

Resources