Receive our weekly advanced programming tips for FREE
03.May
Very usefull jquery commands
0
| 0 votes
Autor: bookkeeper
Chapter: JavaScript

jQuery is very easy to use. You should get familiar with jQuery it will make your life easier!

Select a element:

jQuery('#element_id'); //element with id element_id
jQuery('.class_name'); // all elements with name "class_name"
jQuery('#element_id .class_name'); // all children with class "class_name"

Load when document is finish loading

jQuery().ready(function(){//alias document.onload
  //will be loaded when the document is finish loading
});

Select element with specific attribute

jQuery('form input[type="submit"]'); // select children from form the submit button
jQuery('#form_id input[type="text"]'); //select children from from_id all text input

Select first element

jQuery('ul li:first'); // first li element
jQuery('select option:contains("some_text")'); //select element with text "some_text"
jQuery('form input:disabled'); //select all disabled elements

Add class to element

jQuery('#some_id').addClass('red_class');

Get attribute from element:

jQuery('img').attr('src'); 

Check for class:

jQuery('#some_id').hasClass('some_class'); // true if exist

Get html text

jQuery('#some_id').html() // alias innerHTML
jQuery('#some_id').html("set some text")

Remove class

jQuery('#some_id').removeClass('class_name');

Get and set value

jQuery('#some_id').val(); // get value
jQuery('#some_id').val("some value"); // set value

Toggle a class

jQuery('#some_id').toggleClass('some_class'); //set some_class if not already set

Loop over elements

jQuery('div .sel').each(function(){  

 // do something

});

Hide and show an element

jQuery('#some_id').hide();
jQuery('#some_id').show();

Get parent element

jQuery('#child_id').parent().hide();

Fade in/out an element

jQuery('#some_id').fadeIn('slow'); // slow, fast, ...
jQuery('#some_id').fadeOut('slow'); // slow, fast, ...

Set css an element

jQuery('#some_id').css({ 'height':'40px', 'font-size':'2em' });

Append an element to other

jQuery('<div>something</div>').appendTo('body');

Wrap and unwrap an element

jQuery('#some_id').wrap('<div></div>');
jQuery('#some_id').unwrap();

Get position of an element

var v = jQuery('#some_id').position(); 
v.left;
v.top;

Install an event

var ele = jQuery('#some_id');

ele.click(function(){
  alert("I was clicked");
});

ele.mouseover(function (e){ 
 alert("I was clicked on x: " + e.pageX + " y: " + e.pageY);
});

ele.blur(function (e){
 alert("blur");
});

//etc. http://api.jquery.com/category/events/

AJAX

jQuery().get('/some/url/', function(data){ 
 alert(data); 
});

jQuery().post('/some/url/', {'name':'data'}, function(data){
 alert(data);});

jQuery().loadJSON('/some/url/', function(json_obj){
  alert(json_obj);
});