Sunday, April 15, 2012

Solution to Chapter 5 Exercises of Learning jQuery 3rd Edition




  
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
 



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

1. Alter the code that introduces the back to top links so that the links only appear beginning after the fourth paragraph.

jQuery(document).ready(function ($) { 
    $('<a href="#top">back to top</a>').insertAfter('div.chapter p:gt(2)');
});



2. When a back to top link is clicked, add a new paragraph after the link, containing the message You were here. Ensure that the link still works.

jQuery(document).ready(function ($) { 
    $('a').click(function () {
        $('p:contains("You were here.")').remove();
        $(this).after('<p style=\"color: blue\">You were here.</p>');
    });
});



3. When the author's name is clicked, turn it bold (by adding a tag, rather than manipulating classes or CSS attributes).

jQuery(document).ready(function ($) { 
        $('#f-author').click(function () {
            $(this).wrapAll('<b></b>');
        });
});


4. Challenge: On a subsequent click of the bolded author's name, remove the <b> element that was added (thereby toggling between bold and normal text).

jQuery(document).ready(function ($) { 
    $('#f-author').toggle(
        function () {
            $(this).wrapAll('<b></b>');
        },
        function () {
            $(this).unwrap()
        }
    );
});



5. Challenge: Add a class of inhabitants to each of the chapter's paragraphs, without calling .addClass(). Make sure to preserve any existing classes.

jQuery(document).ready(function ($) { 
    var $chapter_p = $('.chapter p');
    var chapter_p_class = $chapter_p.attr('class')
    $chapter_p.attr({ class: chapter_p_class + ' inhabitants' });
});