jquery if else statement - javascript

What am I doing wrong here? This is on jquery-mobile.
$('.ui-checkbox').click(function() {
if (
$('.ui-checkbox label.ui-checkbox-off').removeClass('off').addClass('on')) {
}else {
$('.ui-checkbox label.ui-checkbox-on').removeClass('on').addClass('off');
}
});
The first portion works, but not when I click a 2nd time.

From your comment, you seem to want
$('.ui-checkbox').click(function() {
$('label.ui-checkbox-on,label.ui-checkbox-off', this)
.toggleClass('on').toggleClass('off');
});
But this is a little strange. You could use a simple class (on) and simply do
$('.ui-checkbox').click(function() {
$('label', this).toggleClass('on');
});
You probably don't need 2 classes as usually "off" means "not on".

Related

How can I make an element appear and disappear using Jquery.

I want to do something like this:
$(document).ready(function(){
if($('.undermenu').css('display','block')){
$('#menu').click(function(){
$('.undermenu').css('display','none');
});
}
else{
$('#menu').click(function(){
$('.undermenu').css('display','block');
});
}
});
This code does not work, but is there any Jquery "effect" or whatever that I can use to hide/un-hide.
For example is there and way to check whether or not display is set to none or block?
Thanks.
Just use toggle():
$('#menu').click(function() {
$('.undermenu').toggle();
});
Though the reason your if($('.undermenu').css('display','block')) didn't work is because you set the display property of the element(s) to block, rather than getting the display property and testing it, which would be:
if ($('.undermenu').css('display') =='block')
If you really want to use an if to test the current display, before modifying the presentation, you'd have to do it inside of the click handler (otherwise it will only run once, on DOMReady, rather than every time):
$('#menu').click(function(){
if ($('.undermenu').css('display') == 'block') {
$('.undermenu').hide();
}
else {
$('.undermenu').show();
}
});
Or, if you want to risk the wrath of your colleagues, you can jazz that up a little:
$('#menu').click(function(){
var undermenu = $('.undermenu');
undermenu[undermenu.css('display') == 'block' ? 'hide' : 'show']();
});
References:
css().
toggle().
You use a setter on your condition :
// This line update .undermenu to display it and return true (return $('.undermenu'), so true)
if($('.undermenu').css('display','block')){
But you must get the value, and test
if($('.undermenu').css('display') === 'block'){
And you code conception is bad. If you do that, you test on document are ready if the .undermenu are displayed or not, and you put a function to the click trigger (to display or to hide..) but ! when your .undermenu was change, you already have the same trigger (to display or hide, and he never change)..
So you need to put your trigger for each click and test the value (displayed or not) on the trigger :
$(document).ready(function(){
$('#menu').click(function(){
if($('.undermenu').css('display') === 'block'){
$('.undermenu').hide();
}
else {
$('.undermenu').show();
}
});
});
On jquery exists:
$("#element_id").show();
$("#element_id").hide();
also you can use:
$("#element_id").fadeIn();
$("#element_id").fadeOut();
This show and hide elements with fade effects.
You can query if the element is hidden:
if($("#element_id").is(":hidden")){
$("#element_id").show():
}
else{
$("#element_id").hide();
}
What you're looking for is .toggle()
$("div").click(function () {
$("img").toggle("slow", function () {
// Animation complete.
});
});
Here is a fiddle: http://jsfiddle.net/FQj89/
You can put the if statement in the function so you don't repeat yourself. You can probably also use toggle(); type stuff depending on what you are doing. ---
$('#menu').click(function(){
if ( $('.undermenu').is(':visible') ) {
$('.undermenu').hide();
else {
$('.undermenu').show();
}
});
This is a good way too, depending on what you are doing though, one may be better than the other.
if ( $('.undermenu').css('display') === 'block' ) { // do something }

Return false not working

Can someone tell me why return false is not working? I just want to check if current is yellow. If it is yellow class don't do nothing (return false). The problem is when you click a button it runs its thing again but I want to avoid that.
Here's the Fiddle of the problem.
/*INSIDE THIS CODE RETURN FALSE NOT WORKING!!*/
$('.yellowcontroll').click(function(){
if($yellow.after('.current').length){
$('.yellow').show();
$('.slideswrapper:not(:animated)').animate({'marginLeft':'-=100'},1000,function(){
$('.current').removeClass('current').hide();
$('.yellow').addClass('current');
$('.slideswrapper').css({'margin-left':'0px'});
if($('.current').is($('.slideswrapper div:last'))){
$('.blue,.green,.red').clone().insertAfter('.slideswrapper div:last');
}
if($('.current').is($('.red'))){
$('.red').prevAll().remove(':not(.yellow)');
$('.yellow').insertAfter($('.slideswrapper div:last'));
}
/*THIS IS NOT WORKING AS EXPECTED!!*/
if($('.current').is($('.yellow'))){
return false;
}
});
}
});
The problem is that you are returning false from the callback to your animation, not the event callback.
If what you are looking for is for nothing to happen when you click the second time then you could move the condition and return false to the front of the click callback:
$('.yellowcontroll').click(function(){
/* MOVE THIS TO THE BEGINNING OF THE CLICK CALLBACK */
if($('.current').is($('.yellow'))){
return false;
}
if($yellow.after('.current').length){
$('.yellow').show();
$('.slideswrapper:not(:animated)').animate({'marginLeft':'-=100'},1000,function(){
$('.current').removeClass('current').hide();
$('.yellow').addClass('current');
$('.slideswrapper').css({'margin-left':'0px'});
if($('.current').is($('.slideswrapper div:last'))){
$('.blue,.green,.red').clone().insertAfter('.slideswrapper div:last');
}
if($('.current').is($('.red'))){
$('.red').prevAll().remove(':not(.yellow)');
$('.yellow').insertAfter($('.slideswrapper div:last'));
}
});
}
});
The code in your fiddle is a mess, but based on your question, it seems that you simply have your logic in the wrong place. Try placing your return false logic at the top of your click event:
$('.yellowcontroll').click(function(){
if($('.current').is($('.yellow'))){
return false;
}
...
});
This fiddle should do what you want.
I think you want to put that code snippet in the beginning of the click handler:
http://jsfiddle.net/mihaifm/3YLEg/2/
$('.yellowcontroll').click(function(){
/*THIS IS NOT WORKING AS EXPECTED!!*/
if($('.current').is($('.yellow'))){
return false;
}
Move the conditional false code to the beginning of the click handler like below and use hasClass like below.
DEMO
if ($('.current').hasClass('yellow')) {
return false;
}
if($('.current').is('.yellow')){
return false;
}

Setting element visiblity with jQuery

Using jQuery, is there some property on an element that I can set to true/false to control the visibility of that element?
Basically, I need something like this:
$(this).visible(someCondition);
toggle() won't work because I need to be able to tell it whether or not it will be shown.
show() and hide() work, but I have to do this:
if (someCondition) {
$(this).show();
}
else {
$(this).hide();
}
Which, as you can see, is not nearly as elegant as the solution I'm looking for.
toggle(someCondition) will work.
It takes an optional boolean parameter.
As SLak suggested, toggle() works. If you are using classes that have visibility states set (i.e., display: none or visibility:hidden), you can also use toggleClass().
jQuery.fn.visibleCond = function( cond ) {
if ( cond ) {
return this.show();
} else {
return this.hide();
};
};
Then:
$(this).visibleCond(someCondition);
And fiddle: http://jsfiddle.net/C3daq/

Can I write this JQuery statement cleaner?

So I have the following:
var box = $(".MyCheckBox");
if (box[0].checked)
{
// Do something
}
else
{
// Do something else
}
Is there a better way of doing this using filters or something?
I know I can go:
$(".MyCheckBox")
.filter(function(index) {
return this.checked;
})
.each(function() {
// do something
});
But I need to do something in the else statement... easier way of doing this? Thanks!
You can use the built-in :checked selector:
$(".MyCheckBox:checked").each(function() {
//Do something with checked ones..
});
$(".MyCheckBox:not(:checked)").each(function() {
//Do something with unchecked ones..
});
Or filter in the each similar to what you have:
$(".MyCheckBox").each(function() {
if($(this).is(":checked")) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});
Or if say you wanted to toggle a class, then use a different approach, this would give the active class to the checked ones:
$(".MyCheckBox").each(function() {
$(this).toggleClass("active", $(this).is(":checked"));
});
Update
Based on comments if you want just raw speed:
$(".MyCheckBox").each(function() {
if(this.checked) {
//Do something with checked ones..
} else {
//Do something with unchecked ones..
}
});
attr('checked') returns the checked value of the first element anyway, so no [0] malarky.
if ($(".MyCheckBox").attr('checked')) {
// Do something
} else {
// else
}
I'd go with Nick's updated answer above, but would like to suggest that you complete your selector. i.e.,
$('input.myCheckBox').each(function(){
// tralalala...
}
... just for the fact that it makes your initial jQuery selection a bit faster. I mean, since we're debating about speed and all. ^_^

Does something like jQuery.toggle(boolean) exist?

I write something similar to the following code a lot. It basically toggles an element based on some condition.
In the following made-up example, the condition is "If the agree checkbox is checked and the name field isn't empty".
$("button").click(function() {
if ($("#agree").is(":checked") && $("#name").val() != "" ) {
$("#mydiv").show();
} else {
$("#mydiv").hide();
}
});
I wish there was some sort of jQuery function that would work like this.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
Is there something like this out there? Or are there other ways besides the first example to do this in a less if-else-ish way?
Ok, so I am an idiot and need to RTM before I ask questions.
jQuery.toggle() allows you to do this out of the box.
$("button").click(function() {
var condition = $("#agree").is(":checked") && $("#name").val() != "" );
$("#mydiv").toggle(condition);
});
First, lets see if I understand what you want to do correctly...
You want to look at the state of a checkbox(checked or not) and hide or show a second div based on the status of that value.
Define this style:
.noDisplay {
display:none;
}
Use this JavaScript:
$("button").click(function() {
$("#mydiv").toggleClass("noDisplay", $("#name").val() == "");
});
The documentation from jQuery on it can be found here:
http://api.jquery.com/toggleClass/
You could write the function yourself.
function toggleIf(element, condition) {
if (condition) { element.show(); }
else { element.hide(); }
}
Then use it like this:
toggleIf($("button"), $("#agree").is(":checked") && $("#name").val() != "");
Syntax 4
$(selector).toggle(display)
display
true - to show the element.
false - to hide the element.
If toggle() is not good for you (e.g. because it animates), you can write a small jQuery plugin, like this:
$.fn.toggleIf = function(showOrHide) {
return this.each(function() {
if (showOrHide) {
return $(this).show();
} else {
return $(this).hide();
}
});
};
and then use it like this:
$(element).toggleIf(condition);

Categories

Resources