The three jquery show/hide methods are all pretty similiar, they show or hide an element, slide
and fade
do so with a nice animation.
Showing an element
// each of these lines accomplishes the same thing!
$('#my-div').show();
$('#my-div').fadeIn();
$('#my-div').slideDown();
Hiding an element
// each of these lines accomplishes the same thing!
$('#my-div').hide();
$('#my-div').fadeOut();
$('#my-div').slideDown();
Toggle
// each of these lines accomplishes the same thing!
$('#my-div').toggle();
$('#my-div').fadeToggle();
$('#my-div').slideToggle();
Note that all these methods will take an optional parameter, duration
, that is the duration of the animation for showing/hiding an element.
This is where things start to get fun! Almost any CSS property can be animated; have fun and try out all sorts of things.
$('#my-div').animate( {/*properties*/}, duration );
Remember that you can chain animations to have them happen in sequence
$('#my-div').animate( {/*first set of properties*/}, duration ).animate({/*second set of properties*/}, duration);
All of these jQuery methods for showing and hiding and animating elements can take an optional last parameter that is a callback function to be run after the animation is complete.
$('#my-div').slideDown(500, function(){
alert('div with the id "my-div" has finished sliding down!');
});
Remember that anything you want to do with the data returned from an ajax request must be done after the ajax request finishes. Most of the time that means it's done inside the ajax .done
callback.
var ajaxTest = 'before ajax request';
$.get('/someurl').done(function(data){
// data.value == 'after ajax request'
ajaxTest = data.value;
});
console.log(ajaxTest); // will print 'before ajax request'
Because the ajax request is performed asynchronously, JavaScript will not wait to execute the code after your ajax request.
To use the values in from our ajax request
var ajaxTest = 'before ajax request';
$.get('/someurl').done(function(data){
// data.value == 'after ajax request'
ajaxTest = data.value;
console.log(ajaxTest); // will print 'after ajax request'
});
console.log(ajaxTest); // will still print 'before ajax request'