Вы находитесь на странице: 1из 8

Check if DOM is ready, If it is ready call a specific function like in case 1 (for example, functionName ) or have anonymous function

loaded like in 2nd case. Case 1: Var functionName = function(){}; $(document).ready (functionName); Case2: $(document).ready(function(){ }); Or $(function(){ });

What's the difference between .closest() and .parents('selector')?

parent returns the immediate parents (one for each element in the caller object) or nothing if the parent does not match the selector. closest returns the closest ancestor matching ancestor for each element (which can be the original element). The third similar function, parents, returns all matching ancestors (not including the element itself).
Self Executing Anonymous function: The first step on the journey to beautiful, modular JavaScript is to learn the art of the self-executing anonymous function. (function(){ console.log('Hello World!'); })(); Lets look at this carefully. This code is made up of two key parts. First is the anonymous function: (function(){ //Normal code goes here }) The really interesting part is what happens when we add this right at the end: (); Those two little brackets cause everything contained in the preceding parentheses to be executed immediately. Whats useful here is that JavaScript has function level scoping. All variables and functions defined within the anonymous function arent available to the code outside of it, effectively using closure to seal itself from the outside world. Lets apply this design patten to our gloriously inane example code. (function(){ var foo = 'Hello'; var bar = 'World!' function baz(){ return foo + ' ' + bar; } })(); 1

//These all throw exceptions: console.log(foo); console.log(bar); console.log(baz()); The last three lines throw exceptions because currently nothing is accessible outside the anonymous function. To allow access to a variable or function, we need to expose it to the global window object. (function(){ var foo = 'Hello'; var bar = 'World!' function baz(){ return foo + ' ' + bar; } window.baz = baz; //Assign 'baz' to the global variable 'baz'... })(); console.log(baz()); //...and now this works. //It's important to note that these still won't work: console.log(foo); console.log(bar); One of the major benefits of this pattern, as seen on the last two lines of the previous example, is that you can limit access to variables and functions within your closure, essentially making them private and only choosing to expose an API of your choice to the global scope. One popular spin on this design pattern, which can be seen in the jQuery source, is to pass in some commonly used objects. In our code we reference window, so lets pass that in as a parameter to the anonymous function. (function(window){ var foo = 'Hello'; var bar = 'World!' function baz(){ return foo + ' ' + bar; } //In this context, 'window' refers to the parameter window.baz = baz; })(window); //Pass in a reference to the global window object When minifying your code, this design pattern will yield great results. All references to window in your code can be renamed to a, for example: (function(a){ console.log(a === window); //Returns 'true' })(window);

Normally youll want to pass in a few objects. A technique you can see used within jQuery itself is to reference an extra parameter that isnt defined when the anonymous function is executed, in effect creating an alias for undefined: (function(window, document, $, undefined){ var foo; console.log(foo === undefined); //Returns 'true' })(window, document, jQuery); You may have noticed that the previous example also aliased jQuery to $, allowing it to play nicely with other frameworks without having to use jQuery in noConflict mode. Its worth pointing out that the parameter names are purely for convention. The following code would work equally as well and serves as a great illustration of whats really going on in this design pattern: (function(mark, loves, drinking, coffee){ mark.open('http://www.google.com'); //window loves.getElementById('menu'); //document drinking('#menu').hide(); //jQuery var foo; console.log(foo === coffee); //undefined })(window, document, jQuery); Although, for obvious reasons, I advise against this The benefits of this design pattern will become even more apparent in later posts. Harnessing the power of selfexecuting anonymous functions will allow you to create more complex but ultimately more intuitive code structures that will make your larger projects much easier to manage. jQuery document.ready vs self calling anonymous function

$(document).ready(function(){ ... }); or short $(function(){...}); -This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.

(function(){ ... })(); - That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act onDOM elements here.

this keyword : refers to the element that triggered the event.

HTML5 data-* Attributes As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification. For example, given the following HTML: <div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div> All of the following jQuery code will work. $("div").data("role") === "page"; $("div").data("lastValue") === 43; $("div").data("hidden") === true; $("div").data("options").name === "John"; Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery). Calling .data() with no parameters retrieves all of the values as a JavaScript object. This object can be safely cached in a variable as long as a new object is not set with .data(obj). Using the object directly to get or set values is faster than making individual calls to .data()to get or set each value: var mydata = $("#mydiv").data(); if ( mydata.count < 9 ) { mydata.count = 43; mydata.status = "embiggened"; } .Siblings() : The siblings( [selector] ) method gets a set of elements containing all of the unique siblings of each of the matched set of elements. It refers to the same elements on the same level. Syntax: Here is the simple syntax to use this method: selector.siblings( [selector] ) Example: $(this).siblings(button).removeattr(disabled);

Parameters: Here is the description of all the parameters used by this method: selector: This is optional selector to filter the sibling Elements with. HTML Lists:

The most common HTML lists are ordered and unordered lists: An ordered list: 1. The first list item 2. The second list item 3. The third list item An unordered list: List item List item List item

HTML Unordered Lists

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag. The list items are marked with bullets (typically small black circles). <ul> <li>Coffee</li> <li>Milk</li> </ul> How the HTML code above looks in a browser:

Coffee Milk

HTML Ordered Lists

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list items are marked with numbers. <ol> <li>Coffee</li> <li>Milk</li> </ol> How the HTML code above looks in a browser: 1. Coffee 2. Milk
HTML Definition Lists

A definition list is a list of items, with a description of each item.The <dl> tag defines a definition list.

The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item in the list): <dl> <dt>Coffee</dt> <dd>- black hot drink</dd> <dt>Milk</dt> <dd>- white cold drink</dd> </dl> How the HTML code above looks in a browser: Coffee - black hot drink Milk - white cold drink
Code to append new <h2> tag to the existing article:

(function(){ $(<h2></h2>,{ text : Hello from Javascript, class : my class }).appendTo(article); .appendTo():

Both jQuery .append() and .appendTo() methods are doing the same task, add a text or html content after the content of the matched elements. The major difference is in the syntax.
$(selector).append(new text); $(new text).appendTo(selector);

Calling .appendTo() on an existing element , moves it to the location specified.


What is the difference between .call and .apply in javascript? While the syntax of call() is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments. Syntax:

.call() fun.call(thisArg[, arg1[, arg2[, ...]]])

.apply() fun.apply(thisArg[, argsArray])

For Example:

var x = 'test', y = 'name', obj = { x: 'value' }; function bar(arg1, arg2){ console.log(this.x, arg1, arg2); } bar.call(obj, x, y); // log 'value', 'test', 'name' bar.apply(obj, [x, y]); // log 'value', 'test', 'name'

You can see from the example that .call methods argument are string and .apply methods argument is an array, this is quite useful when there are many arguments to pass into the function.
How to tell if an element is visible with jQuery Jquery makes it easy to determine if an element is visible or hidden with the is() function. This post shows some examples of how to do this and also how to loop through each of the visible or hidden element s.

Check if an element is visible


In the following HTML the div is initially hidden. It might have also been hidden using jQuery after the page has loaded, or via a toggling function or so on. <div id="foo" style="display:none"></div>
To check if it is visible use the is() function passing ":visible" as the parameter

if( $('#foo').is(':visible') ) { // it's visible, do something } else { // it's not visible so do something else }

Check if an element is hidden This is the same as checking if an element is visible but uses :hidden instead and the logic is the reverse:
if( $('#foo').is(':hidden') ) { // it's hidden, do something } else { // it's not hidden so do something else }

Note: if the element doesn't take up any space in the document, then is(':hidden') will return true even if it is effectively visible. It may be safer to instead do this:
if( !$('#foo').is(':visible') ) { // it's hidden, do something } else {

// it's not hidden so do something else }

Looping though visible elements The next example uses the following HTML:
<div id="foo"> <div>abc</div> <div style="display:none">def</div> <div>ghi</div> </div>

To loop through the visible divs under #foo do something do this:


$("#foo div:visible").each( function() { document.write($(this).html()+'<br />'); });

The above example would write the following out to the document: abc ghi

Вам также может понравиться