Setting element visiblity with jQuery - javascript

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/

Related

JavaScript - If checkbox is disabled, add class using jQuery

I'm having a problem with the syntax (or maybe with the selectors) on my code. See the demo.
I tried the following code but the results does nothing.
#1. hasAttribute():
if ($('input[type=checkbox]').hasAttribute("disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#2. is():
if ($('input[type=checkbox]').is("[disabled]")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
// ------------------------------------------------
if ($('input[type=checkbox]').is(":disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#3. prop():
if ($('input[type=checkbox]').prop("disabled", true)) {
$(this).closest('.chkbox').addClass("is-disabled");
}
So then I think the problem is on the line:
$(this).closest('.chkbox').addClass("is-disabled");
Any idea?
Thanks.
You can use :disabled selector
see here
You're using $(this) without declaring anything. Thats the reason it's not working. It works in the second example because of the .change() function gives the context of the 'thing' (this) that is changing.
This code should work as you desire.
$(function() {
// Grab all inputs with the type checkbox.
var input = $('input[type=checkbox]')
// Check for each of the input fields (i, el stands for index, element)
input.each(function(i, el) {
// Does it have the attribute disabled?
if(el.hasAttribute('disabled')) {
// Add the class 'is-disabled'
$(el).closest('.chkbox').addClass('is-disabled')
}
})
$('input[type=checkbox]').change(function(){
if ($(this).is(":checked")) {
$(this).closest('.chkbox').addClass("is-checked");
} else {
$(this).closest('.chkbox').removeClass("is-checked");
}
});
});

JQuery not removing active class

I'm trying to make my links slide down over the page when the mobile nav is clicked and the content to disappear so only the links are shown. I have got this basically working but the .displayNone class will not remove when I click the mobilenav again and I'm a bit dumfounded as to why.
$(document).ready(function() {
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('.displayNone');
if(status){ $('.wrapper').removeClass('.displayNone'); }
else { $('.wrapper').addClass('displayNone'); }
});
});
Bit of newbie to all this. Anything obvious that anyone can see wrong with this?
Use toggleClass(),
$('.wrapper').toggleClass('displayNone');
And, jQuery's xxxClass() functions expect the name of the class, not the selector, so leave off the . class selector.
When adding/removing classes, just use displayNone, not .displayNone (note the dot!).
Also there's a toggleClass() function which saves you from doing the status thing, which means you just need to do
$('.wrapper').toggleClass('displayNone');
your are doing bit wrong
var status = $('.wrapper').hasClass('.displayNone');
when you use hasClass, addClass or removeClass then you don't need to have '.' dot before class name.
so correct way is
var status = $('.wrapper').hasClass('displayNone');
your code after correction
$(document).ready(function() {
$('#hamburger').on('click', function() {
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('displayNone');
if (status) {
$('.wrapper').removeClass('displayNone');
} else {
$('.wrapper').addClass('displayNone');
}
});
});
You can use :
$('.wrapper').toggleClass("displayNone");
Final code :
$(document).ready(function(){
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
$('.wrapper').toggleClass("displayNone");
})
})

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 }

Toggle attribute(attr) in javascript

I have called this function on onchange event on html checkbox.
When i click for first time all the controls in the table get disabled but when i reclick i want them to enable again.I want it javasrcipt not $("#checkbox1").change
function notewizardcheckbox() {
$('#DispalyTable td').find('*').attr('disabled', "disabled");
}
Plese help me
Thanks in Advance
I'd suggest:
function notewizardcheckbox(el) {
// this does require you to pass in the element, though
var el = el.nodeType && el.nodeType == 1 ? el : false;
if (el === false) {
return false;
}
$('#DisplayTable td').find('*').prop('disabled', !el.checked);
}
Personally, however, I can't see any valid reason not to use the change() method to handle the events, it is definitely valid JavaScript albeit it's a jQuery method, to emulate the onchange/change event.
So, unless you're looking for a plain JavaScript alternative there seems to good reason to avoid it, and even with that requirement, the native events can still be used.
References:
prop().
try with prop() and is(":checked") to check if it is checked or not..
function notewizardcheckbox(obj) {
if($(obj).is(":checked")){
$('#DispalyTable td').find('*').prop('disabled', true);
}else{
$('#DispalyTable td').find('*').prop('disabled', false);
}
}
and make sure you pass this in onchange event onchange=notewizardcheckbox(this)
OR
updated after all the comment i got.. :)
function notewizardcheckbox(obj) {
$('#DispalyTable td').find('*').prop('disabled', obj.checked);
}
try
$("input[type=checkbox]").click(function () {
if($(this).attr('checked',true))
{
$('#DispalyTable td').find('*').attr('disabled', false);
}
else
{
$('#DispalyTable td').find('*').attr('disabled', "disabled");
}
});

Regular Expression: replace everything but not a specific word

I'm trying to perform a simple replace(); method in JavaScript where I'd like to remove every class from an HTML element except a specific one, how can I do it?
I tried this without success:
<div id="my_div" class="hello letsgo baby is_checked cool">Gordon Freeman</div>
<script>
$(document).ready(function () {
alert ($(#my_div).attr("class").replace (/^(is_checked)$/, ""));
// id'like it returns "is_checked" or "" to work like a boolean;
});
</script>
You're trying to alert is_checked when it's there, right? Try using .hasClass:
$(document).ready(function () {
if($("#my_div").hasClass("is_checked")) {
alert("is_checked");
}
else {
alert("");
}
});
If you just want to know whether an element has a certain class on it, this returns true or false telling you exactly that:
$("#my_div").hasClass("is_checked")
$(document).ready(function () {
if ($(this).hasClass('is_checked') {
$(this).removeClass();
$(this).addClass('is_checked');
}
});
if ($(this).hasClass('is_checked'))
$(this).removeClass().addClass('is_checked');
else
$(this).removeClass();
You want to remove every class except a specific one? You can use jQuery's attr() method and define the class specifically:
$('#my_div').attr('class','is_checked');
Here's an example of this in action: http://jsfiddle.net/decHw/
Also important to note that if you wish to select an element in jQuery by its id, you need to wrap it in quotes. You have:
$(#my_div)
It should be:
$('#my_div')

Categories

Resources