My solutions to exercises found in Chapter 3 Handling Events of Learning jQuery 4th Edition by Chaffer and Swedberg.
- When Charles Dickens is clicked, apply the selected style to it.
$('.author').click(function() { $(this).toggleClass('selected') })
- When a chapter title (<h3 class=”chapter-title”>) is double-clicked, toggle the visibility of the chapter text.
$('.chapter-title').click(function() { $(this).nextAll('p').toggleClass('hidden'); })
- When the user presses the right arrow key, cycle to the next body class. The key code for the right arrow key is 39.
var setBodyClass = function() { var body = $('body'); if (body.hasClass('narrow')) { body.removeClass().addClass('large'); } else if (body.hasClass('large')) { body.removeClass(); } else { body.removeClass().addClass('narrow'); } }; $(document).keyup(function(event) { if (event.which == 39) { setBodyClass(); } })
- 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 or Internet Explorer).
Not sure why this is a challenge question. The answer is in the jquery documentation for mouseover$('p').mouseover(function(event) { console.log(event.pageX + " " + event.pageY); });
- Challenge: Use .mousedown() and .mouseup() to track mouse events anywhere on the page. If the mouse button is released above where it was pressed, add the hidden class to all paragraphs. If it is released below where it was pressed, remove the hidden class from all paragraphs.
var down = -1; $(document).mousedown(function(event) { down = event.pageY; }); $(document).mouseup(function(event) { if (down != -1) { var up = event.pageY; if (up < down) { $('p').addClass('hidden'); } else if (up > down) { $('p').removeClass('hidden'); } } });