Wednesday, March 28, 2012

Solution to Chapter 3 Exercises of Learning jQuery 3rd Edition


My solutions to Learning jQuery 3rd Edition Chapter 4 Exercises:
1. When Charles Dickens is clicked, apply the selected style to it.

$(document).ready(function ($) {
    $('.author').click(function () {
        $(this).addClass('selected');
    });
});



2. When a chapter title (<h3 class="chapter-title">) is double-clicked, toggle the visibility of the chapter text. 
(look also at the comments section for a shorter solution to this problem)
$(document).ready(function ($) {
    var toggleVisibility = function () {
        $(this).toggle(
            function () {
                $(this).nextAll().addClass('hidden');
            },
            function () {
                $(this).nextAll().removeClass('hidden');
            }
        );
    };

    $('.chapter-title').dblclick(toggleVisibility);
});



3. When the user presses the right arrow key, cycle to the next body class. The key code for the right arrow key is 39.

$(document).ready(function ($) {
   
var bodyClass = ["default", "narrow", "large"];
    var numberOfBodyClasses = 3;
    var currentBodyClassNumber = 0;


    // setBodyClass() & toggleSwitcher() ARE FROM THE BOOK'S CODE
    // Allow the style switcher to expand and collapse.
    var toggleSwitcher = function (event) {
        if (!$(event.target).is('button')) {
            $('#switcher button').toggleClass('hidden');
        }
    };
    // The setBodyClass() function changes the page style.
    // The style switcher state is also updated.
    var setBodyClass = function (className) {
        $('body').removeClass().addClass(className);

        $('#switcher button').removeClass('selected');
        $('#switcher-' + className).addClass('selected');

        $('#switcher').unbind('click', toggleSwitcher);

        if (className == 'default') {
            $('#switcher').bind('click', toggleSwitcher);
        }
    };

    $(document).keyup(function (event) {
        currentBodyClassNumber = (currentBodyClassNumber + 1) % numberOfBodyClasses;
        if (event.keyCode == 39) // 39 is key code for right arrow key
        {
            setBodyClass(bodyClass[currentBodyClassNumber]);
        }
    });

});


4. Challenge: Use the console.log() function to log the coordinates of the mouse as it moves across any  paragraph. (Note: console.log() displays its results via the Firebug extension for Firefox, Safari's Web Inspector, or the Developer Tools in Chrome).

$(document).ready(function ($) {
    $('p').mousemove(function (event) {
        console.log("Mouse location: (" + event.pageX + ", " + event.pageY + ")");
    });

 });



5. Challenge: Use .mousedown() and .mouseup() to track mouse events anywhere on the page. If the mouse button is released above where it was pressed, then add the hidden class to all paragraphs. If it is released below where it was pressed, then remove the hidden class from all paragraphs.

$(document).ready(function ($) {
    var mouseDownYLocation = 0;

    $(document).mousedown(function (event) {
        mouseDownYLocation = event.pageY;
    });
   
    $(document).mouseup(function (event) {
        if (event.pageY < mouseDownYLocation) //if mouse button is released above where it was pressed
        {
            $('p').addClass('hidden');
        }
       else if(event.pageY > mouseDownYLocation) //if mouse button is released below where it was pressed
        {
            $('p').removeClass('hidden');
        }
    });
});


This is how the page looks after I clicked Charles Dickens (Exer 1), double-clicked Preface (Exer 2), pressed right arrow key once (Exer 3), and moved the mouse across paragraphs (Exer 4).






  
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


10 comments:

  1. Hi Flaga,
    Could you consider using this code for the exercise number 3 (I think it would be much shorter):

    $(document).ready(function() {
    var keyMap = {
    0 : 'default',
    1 : 'narrow',
    2 : 'large',
    i : 1
    }
    $(document).keyup(function(evt){
    if(evt.keyCode == 39) {
    var j = keyMap.i % 3;
    $('body').removeClass().addClass(keyMap[j]);
    keyMap.i ++;
    }
    });

    })

    ReplyDelete
  2. Jeremiah,

    For exercise #2. you could shorten a lot it by using the following three lines.

    $('h3.chapter-title').dblclick(function () {
    $(this).nextAll("p").toggleClass('hidden');
    });

    ReplyDelete
  3. Thanks for sharing - I was stuck on the last one.

    My shorter versions of #1 & #2:
    $('div.author').click(function() {
    $(this).toggleClass('selected');
    });

    $('h3.chapter-title').dblclick(function() {
    $(this).nextAll().toggleClass('hidden');
    });

    Have a great day,
    Elena

    ReplyDelete
  4. BTW, my somewhat ugly solution to #3:

    $(document).keyup(function(event) {
    var key = String.fromCharCode(event.keyCode);
    if (key in triggers) {
    setBodyClass(triggers[key]);
    }
    else if (event.keyCode == 39)
    {
    if( $('body').hasClass('narrow'))
    {
    key='L';
    }
    else if ( $('body').hasClass('large'))
    {
    key='D';
    }
    else
    {
    key='N';

    }
    setBodyClass(triggers[key]);
    }

    });
    I know, not pretty, but it works.

    ReplyDelete
  5. Is something wrong in using in 2. inside the handler:
    $(this).nextAll().toggle();

    Tom

    ReplyDelete
  6. Hey Jeremiah, while there was a more compact solution to #3 listed above, I believe that your code (with only a few minor changes) was more scalable. That is, what if a client wanted to add more classes to the switcher? Here's scaled version below with the added bonus of the Left Arrow key going in reverse. Now, aside from additions to HTML, a coder would only have to add a new class to the bodyClass array:

    $(document).ready(function(){
    // Question 3
    var bodyClass = ["default","narrow","large"];
    var numberOfBodyClasses = bodyClass.length;
    var currentBodyClassNumber = bodyClass.length - 1;

    var toggleSwitcher = function(event){
    if (!$(event.target).is('button')){
    $('#switcher button').toggleClass('hidden');
    }
    };
    var setBodyClass = function (className) {
    var classesToRemove = "";
    for (i=0;i<bodyClass.length;i++){
    classesToRemove += bodyClass[i] + " ";
    }
    $('body').removeClass(classesToRemove).addClass(className);

    $('#switcher button').removeClass('selected');
    $('#switcher-' + className).addClass('selected');

    $('#switcher').unbind('click', toggleSwitcher);

    if (className == 'default'){
    $('#switcher').bind('click', toggleSwitcher);
    }
    };
    $(document).keyup(function(event){

    if (event.keyCode == 39)
    {
    currentBodyClassNumber = (currentBodyClassNumber + 1) % numberOfBodyClasses;
    setBodyClass(bodyClass[currentBodyClassNumber]);
    } else if (event.keyCode == 37){
    currentBodyClassNumber = (currentBodyClassNumber + bodyClass.length - 1) % numberOfBodyClasses;
    setBodyClass(bodyClass[currentBodyClassNumber]);
    }
    });
    });

    ReplyDelete