The jQuery and Javascript code snippets you should learn by heart - developed.be

While jQuery is a great improvement on classic Javascript, it’s still not perfect. What works in version 1.3 doesn’t automatically work in 1.7 and what works in Firefox, doesn’t automatically work in IEx. The syntax isn’t very straightforward and some properties are misleading (eg: .val() vs .value())

This is an updated! incomplete list of stuff I need regularly that works in jQuery/javascript:

DOM Hierarchy

Get an ancestor

$("#element").parents(".these_ancestors")

Get a descendant

$("#element").find(".these_descendants")

Get a sibling

$("#element").siblings(".these_sibblings")

Wait until the DOM-tree is complete (or “page” is loaded)

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

Manipulating DOM tree

Insert something after a certain element

$(".new-html").insertAfter(".what-already-is-in-the-tree");

Insert something right before the closing tag of an element

$(".what-already-is-in-the-tree").append(".new-html");

or

$(".new-html").appendTo(".what-already-is-in-the-tree");

Insert something right after the opening tag of an element

$(".what-already-is-in-the-tree").prepend(".new-html");

or

$(".new-html").prependTo(".what-already-is-in-the-tree");

Visibility

Check if an element is visible

if($('#element').is(':visible')) {

Checkboxes

Check if a checkbox is checked

if($("#checkbox").attr("checked")){

Check a checkbox

$("#checkbox").attr("checked", "checked");

Difference is that you set the “checked” attribute in this example. In the previous example you get the “checked” attribute.

Uncheck a checkbox

$("#checkbox").removeAttr("checked");

Catch the event of (un)checking a checkbox

$("#checkbox").change(function(){
// do stuff here
});

Other form-elements

Get the value of a select form element

$("#select").val();

Catch the event of clicking a button

$("#button").click(function(){
// do stuff here
});

Make sure the textbox is of type “button” and not of type “submit”.

Arrays

Declaring an array

var x = [];
var y = [ 1, 2, 3 ];

Looping through an array.

for (var i = 0; i < a.length; i++) {
 // a[i] is your value
}

Objects

Declaring an object

var x = {};
var y = {
 name: "Robin",
 age: 29
};

Get/set a property of the object

alert(y.name)
y.age += 1; //add one

Random

Yes/no – dialog

confirm("Do&nbsp;you&nbsp;really&nbsp;want&nbsp;this&nbsp;subscription?");

Isn’t jquery, but handy. Returns a boolean.

Ajax with POST-method

$.ajax({
type: "POST",
url: "/theurl",
data: { text: textYouWantToSubmit},
success: function( returnHtml ) {

},
error: function(jqXHR, textStatus, errorThrown){
}
});


Rss Comments

Comments

No comments yet.

Leave a comment