Friday, March 30, 2012

Solution to Chapter 4 Exercises of Learning jQuery 3rd Edition


My solutions to Learning jQuery 3rd Edition Chapter 4 Exercises:

1. Alter the stylesheet to hide the contents of the page initially. When the page is loaded, fade in the contents slowly.

jQuery(document).ready(function ($) {
    $('body').hide().fadeIn(4000);
});



2. Give each paragraph a yellow background only when the mouse is over it.

jQuery(document).ready(function ($) {
    var currentBgColor = $('p').css('background-color');
    $('p').hover(function () {
        $(this).css('background-color', 'yellow');
    }, function () {
        $(this).css('background-color', currentBgColor);
    });
});



3. Make a click of the title (<h2>) simultaneously make it fade to 25% opacity and get a left margin of 20px, then when this is complete, fade the speech text to 50% opacity.

jQuery(document).ready(function ($) {
    $('h2').click(function () {
        $(this).fadeTo('slow', .25).animate({
            marginLeft: '20px'
        }, {
            duration: 'slow',
            queue: false
        }, function () {            // completion callback
            $('.speech').fadeTo('slow', .5)
        });
    });

    //OR
    //    $('h2').click(function () {
    //        $(this).animate({
    //            opacity: 0.25,
    //            marginLeft: '20px'
    //        }, 'slow', function () {
    //            $('.speech').fadeTo('slow', .5)
    //        });
    //    });
});



4. Challenge: React to presses of the arrow keys by smoothly moving the switcher box 20 pixels in the corresponding direction. The key codes for the arrow keys are: 37 (left), 38 (up), 39 (right), and 40 (down).

jQuery(document).ready(function ($) {
    var $switcher = $('#switcher');
    $switcher.css({
        position: 'relative'
    })
    $(document).keyup(function (event) {
        if (event.keyCode == 37) {  // 37 is key code for left arrow key       
            $switcher.animate({
                left: '+=-20px'
            }, 'slow');
        }
        else if (event.keyCode == 38) {  // 38 is key code for up arrow key       
            $switcher.animate({
                top: '+=-20px'
            }, 'slow');
        }
        else if (event.keyCode == 39) {  // 39 is key code for right arrow key       
            $switcher.animate({
                right: '+=-20px'
            }, 'slow');
        }
        else if (event.keyCode == 40) {  // 40 is key code for down arrow key       
            $switcher.animate({
                bottom: '+=-20px'
            }, 'slow');
        }
    });
});



This is a sample screenshot:





  
Free Lessons for Chruch Pianists:
Free lessons, tips and downloads for church pianists

DVD Courses (Reharmonization, Play by Ear!, Arranging, Accompanying, Theory for Church Pianists, etc.):
Over 30 hours of DVD instruction for church pianists
 


Visit Vitabase for Quality Health Supplements