Skip to content

Instantly share code, notes, and snippets.

@zgulde
Last active February 16, 2016 20:44
Show Gist options
  • Save zgulde/2c1fd2054a2c590e702f to your computer and use it in GitHub Desktop.
Save zgulde/2c1fd2054a2c590e702f to your computer and use it in GitHub Desktop.

4.4 Effects Review

4.4.1 - 4.4.3 show/hide fadeIn/fadeOut slideUp/slideDown

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.

4.4.4 Animation

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);

Animation Callbacks

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!');
});

4.5 AJAX Requests Review

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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment