Quantcast
Channel: Dumitru Glavan » javascript
Viewing all articles
Browse latest Browse all 10

jQuery Novice To Ninja – Book Review

$
0
0

jQuery Novice To Ninja Book Review

Recently a friend asked me what will be a good book to start learning jQuery with a more practical approach. My answer was ‘jQuery Novice To Ninja’ by Earle Castledine and Craig Sharkie. It was a really fun book to read with a lot of code examples.

You start by learning about the jQuery syntax, objects and chaining then you go deeply into how to build beautiful animations, custom events and plugins. You are introduced to jQuery UI and how to use it properly.

The book contains a lot of info about Ajax requests and how to handle them easily with jQuery.

In the end you can find some code examples about how to build a rating stars mechanism, some UI tools and plugins.

I also found some code snippets saved from the book that I can share.

Effects

Toggle vieweing with isVisible:

$('#toggleButton').click(function() {
	if ($('#disclaimer').is(':visible')) {
		$('#disclaimer').hide();
	} else {
		$('#disclaimer').show();
	}
});

Animate elements on scroll, make the site header scroll with the page:

$(window).scroll(function() { 
	$('#header').css('top', $(document).scrollTop()); 
});

//or

$(window).scroll(function() {
	$('#header').stop().animate({top: $(document).scrollTop()},'slow','easeOutBack');
});

Scroll to top animation quirck for all browsers:

$('a[href=#]').click(function() {
	$('html, body').animate({scrollTop: 0},'slow'); 
	return false; // Return false to cancel the default link action
}

Switch from fluid to fixed layout:

if ($('body').width() > 900) {
	$('')
	.appendTo('head');
} else {
	$('link[href=wide.css]').remove();
}

Preload images:

$('');

Remove selective elements:

$('#celebs tr').remove(':contains("Singer")');

Timers:

setInterval(function() {
	$('#green').css('left', ++greenLeft);
}, 200);

var redLeft = parseInt($('#red').css('left'));
function moveRed() {
	setTimeout(moveRed, 200);
	$('#red').css('left', ++redLeft);
}
moveRed();

clearInterval();
clearTimeout();

Ajax

Basic usage:

$('#biography').load('computadors.html div:first');
$('div#results').load('search.php', 'q=jQuery&maxResults=10');
$.ajaxSetup({
	type: 'POST'
	url: 'send.php',
	timeout: 3000
});

Access Ajax global events (ajaxSuccess, ajaxSend, ajaxComplete, ajaxError, ajaxStop):

$("#msg").ajaxError(function(event, request, settings) {
	$(this).html("Error requesting page " + settings.url + "!");
});
$('#ajaxInProgress').ajaxStart(function() { 
	$(this).addClass('progress'); 
}).ajaxStop(function() { 
	$(this).removeClass('progress');
});

Get number of ajax requests:

$.active

Load external script in your code:

$.getScript('http://view.jquery.com/trunk/plugins/color/jquery.color.js', function() {
	$('body').animate({'background-color': '#fff'}, 'slow');
});

Plugins

Wrapp your plugin:

function($) {
	// Shell for your plugin code
	$.fn.highlightOnce = function() {
		// Plugin code
	}
})(jQuery);

Set plugin defaults:

$.fn.highlightOnce.defaults = {
	color : '#fff47f',
	duration : 'fast'
};

Create your own selectors:

$.extend($.expr[':'], {
	abovethefold: function(el) { 
		return $(el).offset().top < $(window).scrollTop() + $(window).height();
	}
});

Events

Create event:

// Home-made event object!
var e = $.Event('click');
e.pageX = 100;
e.pageY = 100;
$('p').trigger(e);

Get events with:

$('element').data('events');

Namespace your events:

$('p').bind('mouseover.colorize', function() {
	$(this).css('background-color', 'lemonchiffon') 
}).bind('mouseout.colorize', function() { 
	$(this).css('background-color', '');
}).click(function() {
	$(this).trigger('mouseout.colorize').unbind('.colorize');
});

Trigger non-namespaced events:

$('p').trigger('mouseout!');

Handle custom events like mobile touch events:

$(document).bind('touchstart', function(e) {
	var original = e.originalEvent;
	var x = original.changedTouches[0].pageX;
	var y = original.changedTouches[0].pageY;
	$('#block').css({top: y, left: x});
});

Define your sepcial events (never used this):

jQuery.event.special.multihover = {
	setup: function(data, namespaces) {
	// Do when the first event is bound
	},
	add: function(handler, data, namespaces) {
		// Do every time you bind another event
	},
	remove: function(namespaces) {
		// Do when an event is unbound
	},
	teardown: function(namespaces) {
		// Do when the last event is unbound
	},
	handler: function(e) {
		// Do your logic
	}
}

Other stuff

Use .one(‘mouseover’, function (){}) to bind the event once.

Call functions with call to pass the scope:

// Fire the setUp callback in a plugin
$.isFunction(options.setup) && options.setup.call(this);

Use utility functions:

$.isArray(), $.isFunction(), $.isEmptyObject(), $.isPlainObject()

Use andSelf to add current elemnt to the jQuery selector:

$(this).prevAll().andSelf().addClass('rating-over');

Use attributes functions to filter elements:

$(list).children().attr('selected', function(i, selected) {
	return !selected;
});

Use toggleClass with function:

$(this).toggleClass('opened', x == 1);

Use pushStack to add elements to the stack:

jQuery.fn.surrounds = function() {
	var prev = this.index() == 0 ? 
	this.siblings(':last') : 
	this.prev();
	var next = this.index() == this.siblings().length ? 
	this.siblings(':first') : 
	this.next();
	var newStack = prev.add(next);
	return this.pushStack(newStack, 'surrounds', '');
};
$('#categories li:first').surrounds().css('color', 'red').end().css('color', 'blue');

Some knowledge about Javascript bad parts:

JavaScript treats all these values as truthy:

  • true
  • 1 (because it’s a non-zero number)
  • ’0′ (because it’s a non-empty string)
  • ‘false’ (because it’s a non-empty string)
  • function() {} (any function)
  • {} (any object)
  • [] (any array)

And these values are falsy:

  • false
  • 0 (the number zero)
  • ” (an empty string)
  • null
  • undefined
  • NaN (a special number value meaning Not a Number)

Nice book to begin learning jQuery. What else can you recommend?


Viewing all articles
Browse latest Browse all 10

Trending Articles