Skip to content

Instantly share code, notes, and snippets.

@anantja-in
Last active August 20, 2019 17:09
Show Gist options
  • Save anantja-in/c56982bca093ef715838 to your computer and use it in GitHub Desktop.
Save anantja-in/c56982bca093ef715838 to your computer and use it in GitHub Desktop.
A long long time ago, I learnt jQuery and made these notes. They used to be helpful in the earliest days when I was still getting used to programming the web.

Introduction

The following two do the same thing:

$(document).ready(function() {});
$(function() {});

Essentials

$("#third").toggleClass("striped");
$("p").size() // returns the number of <p> elements in the document
$("p.second").addClass("striped");
$("p:first").css("font-style", "italic"); // first is a positional selector
$("p.last").hide(); // or $("p.last").show();
$("p")[0].innerHTML="<i> Hello world! </i>";
$("body div p").toggleClass("striped"); //Specifying elements in a heirarchy
$("#first").slideUp("slow"); //Sliding elements up (and down)
$("<p>New para</p>").insertAfter("#first"); //Create new HTML; insertBefore()

Selectors

x y means x is an ancestor of y
x > y means x is a direct parent of y 
:eq(index) means get the (index+1)th element. 0-indexed.
:gt(index) and :lt(index)
:even and :odd
[attribute]
[attribute=value] // Also, != ^= $= *=
:first-child, :last-child and :nth-child(index/even/odd/equation)
:radio // select all radio buttons
:checkbox
:enabled and :disabled
:checked and :selected
$("p:first-child") //select all <p> that are first child of their parent
$("p:last-child") // select all <p> that are last child of their parent
$("p:nth-child(3)") // select all <p> that are 3rd child of their parent
$("p.contains('Haha')") // select all <p> that contain 'Haha' in the text
$("p[language]") // selects all <p> elements which have language attribute
//This means <p language="English">Haha</p> would get selected
if($("#p1").is("p")) {} //checks if the selected element is of the correct type
$("p:eq(2)") // select the third <p> element
$('input:checked').length //returns the number of checked elements.
$("select option:selected")//For a list box
// <form><select size="4" multiple="true"><option>1</option>..</select></form>

Retreival and manipulation

//html() and text() functions are compliant with all browsers
//innerHTML(), outerHTML(), innerText(), outerText() - not so much
//jq width() and height() functions always work - even if you didn't set them
$("img").each(function(m) {
	this.alt="Image "+(m+1);
}); //each

//Get an attribute
$("img:first").attr("alt") //returns the alt attr for the first img element
//Here $("img")[0].attr("alt") won't work since [0] returns a browser element
$("img").slice(0,1).attr("alt") //slice(m,n) returns the m..n-1 elements

//Set an attribute
$("img:first").attr("alt", "Set this alt to this");

//Replace all divs by spans
$("div").html("<span> Here is a span </span>");

//Replace the text and not HTML of an element
//In the following, you actually see <span>.. in the browser window
$("div").text("<span> Here is a span </span>");

$("p").append("<b>$1,000,000,000</b>");
$("p:last").append($("p:first"));

$("img").width(500) //in pixels. Also, height.
$("p").wrap("<h1></h1>"); //wrap all <p> in <h1>

$("#target").before("<p>This appears before target</p>");
// Just like append; also, before()

//For getting and setting value attribute of elements
$("target").val("Hello there")
var val_target = $("#target").val();

Event Handling

//Start with binding an event handler to an element
$("img").bind(event, [data], handler) //data is optional
//event can be "blur", "focus", "load", "resize", "scroll", "unload", "before-unload", "click", "dblclick", "mousedown", "mouseup", "mousemove", "mouseover", "mouseout", "mouseenter", "mouseleave", "select", "change", "submit", "keydown", "keyup", "keypress" and "error"

//Bind mutiple event handlers to one event
$(#target)
	.bind('click', function(event) {
		alert("Hello!");
	})
	.bind('click', function(event) {
		alert("Is there anybody out there?");
	});

//The above is equivalent to:
$("#target")
	.click(function(event) {
		alert("Hello!");
	})
	.click(function(event) {
		alert("Is there anybody out there?");
	}); //Just use the event name and don't pass any event

//To run the bound function only once (say, initialization): ues one()
$("#target")
	.one('click', function(event) {
		alert("Hello!");
	});

//Unbinding event handlers:
$("#target").unbind('click', clicker);

//Using the event object: some event properties: event.x, x= { altKey, controlKey, data, keyCode, pageX, pageY, relatedTarget, result, screenX, screenY, shiftKey, target, timeStamp, type}
//Also, look at Event Object Methods

//event.type gives the event's type

//Capturing keystrokes in the event handler:
function typer(event) {
	$('#p1').text('Character: '+String.fromCharCode(event.keyCode));
}


//Capturing hover events. Need to pass two handler functions in this one
$('#target').hover(over,out);
function over(event) {...}
function out(event) {...}

//event.target.id gives the id of the element that initiated the event

Visual Effects and Animation

{show,hide,toggle}(duration, callback) Both parameters are optional
$('#target').show();
$('#target').hide();
$('#target').show(1000,callback_function) //No () after callback function name
$('h2').toggle(); //toggles the visibility.

slide{Up,Down,Toggle}(duration,callback) like show() - makes it visible
$('#first').slideUp('slow');

{fadeIn,fadeOut}(duration,callback) //All parameters are optional
fadeTo(duration, opacity, callback) //All parameters are optional

//Creating custom animation
animate(params, duration, easing, callback). For example:

$('#target').animate( {
	width: "80%",
	opacity: 0.333
}, 2000);

jQuery Utility Functions

//These are the functions named jQuery.XXX(). Can be referred as $.XXX()

//Convert lists, maps, named node maps etc. into standard js array
var array = $.makeArray(document.getElementByTagName("p"));
array.reverse();
$(array).appendTo(document.body);


//Searching an array
$.inArray(searchTerm, array) //returns 0-based index of first match or -1

//Filtering an array
array = $.grep(array, function(n,i) {
	return (i>4);
});
array = $.grep(array, function(n) {
	return n!=7;
});

array.join(", ") //returns a comma separated string of array elements

//Eliminating duplicate elements from an array
var array = $("p").get(); //gets all the <p> elements
array = array.concat($(".duplicateMe").get());
array = $.unique(array); //New array has only unique elements
//NOTE: This works only with page elements and not general array elements

//Checking whether Data is an Array, a function or something else
$.isArray()
$.isFunction()

//Mapping an array with $.map(). Double each element of the array:
array = $.map(array, function(n,val) {
	return val+val;
});

//Iterating with $.each()
var obj= {one:1, two:2, three:3};
$.each(obj, function(i,val) {
	//here, refer to the item with i and its value by val
	$('#'+i).append(document.createTextNode ("Property "+i+" has value "+val));
});

//Trimming text. Like strip() of python
text = $.trim(text);

//Checking browser support for various features
$.support.XXX //To check if the browser supports a particular feature. Example:
if ($.support.boxModel) {
	$("p").html("Something");
}

//Some variables
$.browser //is an object with the following structure
//(bool)safari, (bool)opera, (bool)msie, (bool)mozilla, (string)version

AJAX

//Using AJAX the old way (DIY way):
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
	XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
	XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID) {//dataSource is a message.txt on server
	if (XMLHttpRequestObject) {
		var obj = document.getElementById(divID);
		XMLHttpRequestObject.open("GET", dataSource);
		XMLHttpRequestObject.onreadystatechange = function() {
			if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status==200) {
				obj.innerHTML = XMLHttpRequestObject.responseText;
			}
		}
		XMLHttpRequestObject.send(null);
	}
}
//In the form input tag: onclick="getData('message.txt', 'targetDiv')"

//Using jQuery load() to implement Ajax:
//Format: load(url ,parameters, callback)
$("div").load("message.txt"); //that's it :D

//Passing data to the server
//If you include parameters, jQ makes a POST request to the server, else GET
$("div").load("poster.php", {data:1});

//Passing Form Data to the server
//The serializeArray() function creates an object whose properties correspond to the names of the controls in a form. Thus, easy to send in a whole form.
$("div").load("poster.php", $("#targetForm").serializeArray());

//Using $.post() to send data to the server and $.get() to get it. 
//Both $.get() and $.post() have same arguments as load()
//load() shoves the data into an element set which might not be always desired.
$.post("poster.php", {data:1}, function(data_received) {
	$("div").text(data_received);
});
$.get("message.txt", function(data_received) {
	$("div").text(data_received);
});

//Using GET to send the data to the server. When you do that, the data is appended to the URL like http://x.com/pagename?data=1. POST uses HTTP headers giving security.
$.get("getter.php", {data:1}, function(data_received) {
	$("div").text(data_received);
});

//$.ajax() (since load(), $.get() and $.post() are just quick shortcuts.)
//$.ajax() offers 20 such options. Full list: Table 8.1. Some examples:

$.ajax({
	type: 'GET',
	url: 'message.txt',
	success: callback
})

function callback(data, status) {
	$("div").text(data);
}

$.ajax({
	type: 'POST',
	url: 'poster.php',
	data: {data:1},
	success: callback
});


//Handling AJAX errors:
$.ajax({
	type: "GET",
	url: "getter.php",
	data: {data:1},
	success: callback,
	timeout: 10, //10 milliseconds
	error: err
});

function err(xhr, reason, ex) { //ex is the exception object
	$("div").text(reason);
}

//Handling XML (and put the XML response in a <select> control)
$.ajax({
	type: "GET",
	url: "sandwiches.xml",
	dataType: "xml",
	success: callback
});

function callback(data, status) {
	var sandwiches = data.getElementByTagName("sandwich"); // <sandwich> tags
	listSandwiches(sandwiches);
}

function listSandwiches(sandwiches) {
	var loopIndex;
	var selectControl = document.getElementById("sandwichList");
	for (loopIndex=0; loopIndex<sandwiches.length; loopIndex++) {
		selectControl.options[loopIndex] = new Option(sandwiches[loopIndex].firstChild.data);
	}
}

//Handling Ajax events globally
AjaxStart(), AjaxSend(), AjaxSuccess(), AjaxError(), AjaxComplete(), AjaxStop()
//Example:
$("#starting").bind("ajaxStart", function() {
	$(this).show();
});

jQuery Widgets

//A widget is a control (controls are textboxes, listboxes, buttons etc.)
//Need to include the following for these examples to work:
ui.all.css, jquery-[ver].js, ui.core.js, ui.datepicker.js

//Accordion
$(document).ready(function() {
	$("#accordion").accordion();
})
//In HTML:
<div id="accordion">
	<h3><a href="#">Section 1</a></h3>
	<div>
		This is the first section.
	</div>
	...
</div>

//DataPicker
$("#datepicker").datepicker({onSelect: function(dateText, inst) {
	$("#result").text("You selected" + dateText); 
}}); //inst is an object corresponsing to the datepicker widget
//In HTML:
<div type="text" id="datepicker"></div>

//Dialog
//include draggable.js, resizable.js, dialog.js
$("#dialog").dialog({
	buttons: {"Ok": function() {
		$(this).dialog("close");}},
	beforeclose: function(event, ui) {
		$("#results").text("You entered "+$("#text").val())
	}
});
//In HTML:
<div id="dialog" title="Dialog Title">
	<input type="text" id="text"></input>
</div>
<div id="results"></div>

//ProgressBar
function increase() {
$("#progressbar").progressbar({
	value:30});
}
//In HTML:
<div id="progressbar"></div>

//Slider
$("#slider").slider({
	min:0,
	max:100,
	slide: function(event, ui) {
		$("#results").text("Slider is at value "+$("#slider").slider('value'))
	}
});

//Tabs
$("#tabs").tabs();
//In HTML:
<div id="tabs">
	<ul>
		<li><a href="#fragment-1"><span>Item One</span></a></li>
	</ul>
	<div id="fragment-1"><p>This is Item one.</p></div>
</div>


//Some tips:
// cache divs when you first do some action on them
var someDiv = $('#someDiv').hide();  

//use Find:
// Fine in modern browsers, though Sizzle does begin "running"  
$('#someDiv p.someClass').hide();  
  // Better for all browsers, and Sizzle never inits.  
$('#someDiv').find('p.someClass').hide();  

// Context instead:
$('#someContainer')  
  .find('.someElements')  
  .hide(); 

//Don't abuse $(this)
$('#someAnchor').click(function() {  
    alert( this.id );  // better than alert( $(this).attr('id') ); 
});  
// Always access href, src and style attributes via jq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment