Getting Started with jQuery
Topics
-
jQuery selectors
-
class selectors
-
id selectors
-
other selectors
-
-
DOM Manipulation
-
addClass
-
append
-
attr
-
html
-
text
-
hide and show
-
-
Event Handlers
- click
- change
- isdefaultprevented
- focus and blur
- keyboard events(keypress, keyup, keydown)
- mouse events(mousein, mouse out, mousemove, hover)
- jQuery GET/POST
jQuery selectors
-
Class selectors
-
$('.classname')
-
-
ID selectors
-
$('#id')
-
-
element selectors
-
$(p)
-
-
input selectors
-
$('input [type=text]')
-
-
first and last
-
$('li:first') or $('li:last')
-
DOM Manipulation
Note: selector can be any possible selector.
-
Hide and Show
-
$(selector).hide()
-
$(selector).show()
-
-
addClass
-
$(selector).addClass('wrap')
-
-
append
-
$('ol').append('<li>new list item</li>')
-
-
appendTo
-
$('<li>new list item</li>').appendTo('ol')
-
-
after and before
-
$(selector).after('hello')
-
$(selector).before('hello')
-
-
html() - gives you the html content of the selector
-
$(selector).html()
-
-
text() -gives you the text content of the selector
-
$(selector).text()
-
-
val() - gives you the value of the form elements
-
$('input').val()
-
-
val(value) - sets the value to the form elements
-
$('input').val('hello')
-
Text
Text
more tags...
-
attr('title') - gets the value of the attribute
-
$(selector).attr('title')
-
-
attr('title', 'value') -sets the value to an attribute
-
$(selector).attr('title','hello world')
-
-
removeAttr() -used to remove an attribute
-
$(selector).removeAttr( "title" )
-
some more tags...
Event Handlers
- Mouse Events
- click
- dblclick
- mouseenter
- mouseleave
- mousemove
- Keyboard Events
- keypress
- keyup
- keydown
- Form Events
- submit
- change
- focus
- blur
General format for writing an event:
$(selector).on('eventname',function(context,event){
//do something
});
Good practices, Performance and Memory management!
- place styles at the top of the html page
- place scripts at the bottom of the html page
- use external files to write your js and css code
- The html page should have a 'lang' attribute.
- html page should have a 'main' section with role='main'
- eg: <main role='main'> </main>
- use CDN libraries whereever possible
- Local variables are fast
- accessing object is very expensive
- prefer to use object.name instead of object["name"] because it is faster on safari
var firstDiv=document.getElementById("first")
var secondDiv=document.getElementById("second")
var thirdDiv=document.getElementById("third")
***Never ever make this mistake***
- store in a variable when an object is accessed more than once
var doc=document
var firstDiv=doc.getElementById("first")
var secondDiv=doc.getElementById("second")
var thirdDiv=doc.getElementById("third")
Write this instead...
- use 'ySlow' addon to check out the improvements you can do with your html page.
Intro to jQuery and Performance Improvement in javascript
By Santosh Viswanatham
Intro to jQuery and Performance Improvement in javascript
- 1,546