jQuery
- jQuery basics: http://jqfundamentals.com/chapter/jquery-basics
- $(): can take these things:
- CSS selectors
- HTML
- JavaScript Object
- jQuery select elements the same way CSS does
- Direct to another page:
$('button selector').click(function(){ document.location.href='the_link_to_go_to.html'; })
- Example:
$("#myTop").css({"background-color","blue"});
// set multiple attributes:
css({"propertyname":"value","propertyname":"value",...}); - text(): When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed). When this method is used to set content, it overwrites the content of ALL matched elements.
- Binding an event:
$("element").click(function(){ alert($(this).text()); }); // for elements existed already $("element").bind('click', function(){ alert($(this).text()); })
jQuery events: form; document loading, browser, mouse, keyboard
- You can call document.ready multiple times, and jQuery will chain together each one to be called in succession.
- unbind: In the simplest case, with no arguments,
.unbind()
removes all handlers attached to the elements$("myElement").bind("click", function(){ alert("something"); }) $("myElement").unbind("click"); // or $("myElement").unbind(); // unbind all element events
- n-th child selector: things start at 1 other than 0:
$("document").ready(function(){ $("ul li:nth-child(2n)").css('border', '2px solid red'); }); // n start counting at 1
- The
$.contains()
method returnstrue
if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returnsfalse
. Only element nodes are supported; if the second argument is a text or comment node,$.contains()
will returnfalse
. - this and $(this): this is a keyword of javascript, $(this) is wrapped with jquery, so it has jquery properties and methods like $(this).attr('id') which equals this.getElementById();
- If you don't tell a function what value to return, it will return a value of
- .before methods insert content before the specified element:
$("button").click(function(){ $("p").before("<p>Hello world!</p>"); });
- length property, size(), get() function:
var elems = $("p").length; // equals $("p").size()
// get(), will return an array of DOM elements instead of jQuery wrapped array
var elems2 = $("li").get(); // get() method can specify the index of the outcome: $("li").get(0);
$('ul').find('li.b').css('border', '3px solid red'); // find <li> item inside <ul> which have b class
$('p').each(function(){
// code to proceed
}); - .hover(handlerIn(eventObject), handlerOut(eventObject)): the two arguments are of type function, which is executed when mouse enters or leaves.
- remove() and detach(), empty(): remove will delete the DOM element, and detach will hold on to it and can restore for you later. empty() method removes the contents of selected elements: $("p").empty();
- Traversal: .parent(), .children([selector]), .prev(), .next(): .children() do not return text node. parents() returns parents of selected elements. siblings() return all same level DOM elements except itself. children() select next level of DOM.
- Arrays don’t have to start with a dollar sign ($). The practice of indicating a jQuery array with a dollar sign is a coding convention of jQuery developers.
- $(selector).replaceWith(content) method, one-to-one exchange:
- before and after methods:
$('.meat').before('<li>tofu</li>'); $('.meat').after('<li>tofu</li>');
- filter methods:
- first: $('menu_list').children().first();
- last: $('menu_list').children().last();
- eq: $('menu_list').children().eq(0); // first element
- slice: keep elements between given index(exclusive both ends), $('menu_list').children().slice(1,3); returns the second one
- filter: keep matched elements of the selector,
- not: filter out everything that does not match the selector
- fadeIn, fadeOut, fadeTo(lets you animate the selected element to a specific opacity percentage); slideUp, slideDown, slideToggle;
// fadeIn syntax: $(selector).fadeIn(speed,callback); $("lightning").fadeIn('fast"); // string of slow, normal, fast $("lightning").fadeIn(1000); // milliseconds // default speed is normal, which is 0.4 seconds
- animate: this method only work on CSS properties that use numbers for their settings:
// syntax: $("selector").animate(property [,duration][,easing][,callback])
$("#my_div").animate({left:"100px"}, 500); // the first parameter is required while the second is optional, the first part is // the CSS property you want to animate, the second is duration
$("#my_div").animate({
opacity:0,
width:"200px",
height:"800px"
}, 500) // you can set multiple at one time - relative operator:
$("#box").animate({left:"+=20"})
- Disable animation: jQuery.fx.off
<body> <p><input type="button" value="Run"/> <button>Toggle fx</button></p> <div></div> <script> var toggleFx = function() { $.fx.off = !$.fx.off; }; toggleFx(); $("button").click(toggleFx) $("input").click(function(){ $("div").toggle("slow"); }); </script> </body>
- Difference between DOM standards and CSS standards: http://www.oxfordu.net/webdesign/dom/straight_text.html
- Object constructor:
function MyPerson(a, b){ this.name = a; this.age = b; }
var myperson = new MyPerson('Jo', 14); - Create element:
var newItem = $("<p>This is a paragraph</p>"); $("#para2").html(newItem); // .html() grabs the first match item and return or change the content, similar method is .text()
- Manipulating attributes:
1 attr(name) // accesses property on the first matched element 2 attr(properties) // sets a series of attributes on all matched elements, for example 3 attr({src:"images/img.jpg", alt:"some text"}) 4 attr(key, value) // set value to an attribute 5 attr(key, fn) 6 removeAttr(name)
$(document).ready(
$("a").attr("target", "_blank"); // access all links and open it in new window
) - $.inArray: return the index of a value, -1 if not found:
var index = $.inArray(value, array); // var index = $.inArray('needle', haystack);
- To empty an array you just need to set the length to 0:
var used_cards = new Array('needle', 'heel', 'hello'); used_cards.length = 0;
- window object is the topmost object of the javascript world. It has methods and properties:
window.name // a property let us set or access the name of the window window.history // a property that let us access the different URLs loaded over time window.document // a property refers to the main content of the loaded document window.onfocus // detects the current active window window.onblur // when window loses focus window.setTimeout(); window.clearTimeout(); window.setInterval(); window.clearInterval();
- Inserting content:
- CSS:
addClass(class) // adds the specified class to each of the set of matched elements hasClass(class) // returns true if the specified class is present on at least one of the set of matched elements removeClass(class); toggleClass(class) // Adds the specified class if it is not present, removes the specified class if present toggleClass(class, switch) // Adds the specified class if switch is true, otherwise removes the class
- window.onblur, window.onfocus:
$("document").ready( window.onblur = blurMe; window.onfocus = focusMe; function blurMe(){ // code; } // code )
- setTimeout, clearTimeout, setInterval, clearInterval(javascript methods); delay()(jQuery method):
setTimeout(myFunction, 4000); // wait some time until ... setInterval(repeatMe, 1000); // repeat after some time slideDown().delay(5000).slideUp(); // pause between effects that are queued up in a chain of effects
// use clearInterval to clear repeated effects:
myInterval = setInterval(repeatMe, 4000);
clearInterval(myInterval);
Notice: setTimeout and setInterval are methods specific to window object, but they can be called without window prefix - Math.random() : produces [0, 1)
- jQuery variable:
.click(function(){ var $this = $( this ); });
$this is a jQuery variable, $ make it a notation for jQuery variable(wrapper)
- get time:
function getTime(){ var a_p = ""; var d = new Date(); var curr_hour = d.getHours(); (curr_hour < 12) ? a_p = "AM" : a_p = "PM"; (curr_hour == 0) ? curr_hour = 12 : curr_hour = curr_hour; (curr_hour > 12) ? curr_hour = curr_hour - 12 : curr_hour = curr_hour; var curr_min = d.getMinutes().toString(); var curr_sec = d.getSeconds().toString(); if (curr_min.length == 1) { curr_min = "0" + curr_min; } if (curr_sec.length == 1) { curr_sec = "0" + curr_sec; } $('#updatedTime').html(curr_hour + ":" + curr_min + ":" + curr_sec + " " + a_p ); }
- .load(): pass into it URL to insert into the specified element:
$("#feeds").load("feeds.html");
- $() is short for $(document).ready();
- test element:
if ( $( '#nonexistent' ).length ) { // This code will only run if there's a matching element } if ( $( '#nonexistent' ) ) { // Wrong! This code will always run! }
- Getters, Setters: There are many methods you can call once you've made a selection. These methods generally fall into two categories: getters and setters. Getters retrieve a piece of information from the selection, and setters alter the selection in some way. In almost all cases, getters operate only on the first element in a selection (
.text()
is a notable exception); setters operate on all elements in a selection, using what's known as implicit iteration. - ajax:
-
- $.get
- $.getJSON
- $.getScript
- $.post
- $.load
- n
- n