How can I change CSS display none or block property using jQuery?
14 Answers
The correct way to do this is to use show
and hide
:
$('#id').hide();
$('#id').show();
An alternate way is to use the jQuery css method:
$("#id").css("display", "none");
$("#id").css("display", "block");
There are several ways to accomplish this, each with its own intended purpose.
1.) To use inline while simply assigning an element a list of things to do
$('#ele_id').css('display', 'block').animate(....
$('#ele_id').css('display', 'none').animate(....
2.) To use while setting multiple CSS properties
$('#ele_id').css({
display: 'none'
height: 100px,
width: 100px
});
$('#ele_id').css({
display: 'block'
height: 100px,
width: 100px
});
3.) To dynamically call on command
$('#ele_id').show();
$('#ele_id').hide();
4.) To dynamically toggle between block and none, if it's a div
$('#ele_id').toggle();
(function($){
$.fn.displayChange = function(fn){
$this = $(this);
var state = {};
state.old = $this.css('display');
var intervalID = setInterval(function(){
if( $this.css('display') != state.old ){
state.change = $this.css('display');
fn(state);
state.old = $this.css('display');
}
}, 100);
}
$(function(){
var tag = $('#content');
tag.displayChange(function(obj){
console.log(obj);
});
})
})(jQuery);
In my case I was doing show / hide elements of a form according to whether an input element was empty or not, so that when hiding the elements the element following the hidden ones was repositioned occupying its space it was necessary to do a float: left of the element of such an element. Even using a plugin as dependsOn it was necessary to use float.