Oleh Rovenskyi
CORE
BASIC
How jQuery Connect
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.11.1.js">
</script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<script src="js/jquery.js"></script>
<script>
// Your code goes here.
</script>
</body>
</html>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.11.1.min.js">
</script>
<script type="text/javascript"
src="http://code.jquery.com/jquery-2.1.1.js">
</script>
jQuery the Basics
Use CDN
jQuery 1.11 and jQuery 2.1Released
How use jQuery
Launching Code on Document Ready
Native JavaScript
window.onload = function() {
alert( "welcome" );
};
jQuery
$( document ).ready(function() {
// Your code here.
});
$() — synonym for jQuery()
$(function() {
// Your code here.
});
Avoiding Conflicts with Other Libraries
Putting jQuery Into No-Conflict Mode
When you put jQuery into no-conflict mode, you have the option of assigning a new variable name to replace the $ alias.
<script>
(function($) {
$(function() {
$("div").hide();
});
})(jQuery);
</script>
Use anonymous function
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j( "div" ).hide();
});
window.onload = function() {
var mainDiv = $( "main" );
}
</script>
Selecting Elements
$("#content") // select elements with id=content
$("div#content") // select div with id=content
$(".wrapper") // select elements with class=wrapper
$("div.wrapper") // select div with class=wrapper
$(".wrapper.box") // select elements with class=wrapper and box
$("h2") // select all tags h2
$("h1, h2") // select all h1 and h2
$("input[name='first_name']"); // Selecting all input elements by Attribute
$("[name='first_name']"); // Selecting all elements by Attribute
Pseudo-Selectors
$("a.external:first");
$("#myForm :input"); // Select all input-like elements in a form.
$("div:animated"); // All currently animated divs.
$("h1 + p")
$("#stick ~ article")
$("#stick").prev()
$("#stick").next()
$("div article h2") vs $("article").find("h2")
Text
Searching the DOM
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2>
<p>Plan your next adventure.</p>
<ul id="destinations">
<li>Rome</li>
<li>Paris</li>
<li class='promo'>Rio</li>
</ul>
Using the descendant selector
Text
Selecting direct children
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2>
<p>Plan your next adventure.</p>
<ul id="destinations">
<li>Rome</li>
<li>
<ul id="france">
<li>Paris</li>
</ul>
</li>
<li class='promo'>Rio</li>
</ul>
Searching the DOM
Text
Selecting only direct children
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2>
<p>Plan your next adventure.</p>
<ul id="destinations">
<li>Rome</li>
<li>
<ul id="france">
<li>Paris</li>
</ul>
</li>
<li class='promo'>Rio</li>
</div>
Searching the DOM
Selecting multiple elements
<h1>Where do you want to go?</h1>
<h2>Travel Destinations</h2>
<p>Plan your next adventure.</p>
<ul id="destinations">
<li>Rome</li>
<li>
<ul id="france">
<li>Paris</li>
</ul>
</li>
<li class='promo'>Rio</li>
</ul>
Searching the DOM
Traversing
Filtering by traversing
It takes a bit more code, but it’s faster.
Traversing
Filtering by traversing
$("li").first();
$("li").first().next();
Traversing
Walking up the DOM
$("li").first();
$("li").first().parent();
Traversing
Walking the DOM up and down
$("#destinations").children("li");
children(), unlike find(), only selects direct children
Traversing
Parents
<div class="grandparent">
<div class="parent">
<div class="child">
<span class="subchild"></span>
</div>
</div>
<div class="surrogateParent1"></div>
<div class="surrogateParent2"></div>
</div>
// returns [ div.child ]
$( "span.subchild" ).parent();
// Selecting all the parents of an element that match a given selector:
// returns [ div.parent ]
$( "span.subchild" ).parents( "div.parent" );
// returns [ div.child, div.parent, div.grandparent ]
$( "span.subchild" ).parents();
// Selecting all the parents of an element up to, but *not including* the selector:
// returns [ div.child, div.parent ]
$( "span.subchild" ).parentsUntil( "div.grandparent" );
// Selecting the closest parent, note that only one parent will be selected
// and that the initial element itself is included in the search:
// returns [ div.child ]
$( "span.subchild" ).closest( "div" );
// returns [ div.child ] as the selector is also included in the search:
$( "div.child" ).closest( "div" );
Attributes
The .attr() method
.attr() as a setter:
$( "a" ).attr( "key", "value" );
$( "a" ).attr({
title: "all titles are the same too!",
href: "somethingNew.html"
});
.attr() as a getter:
$( "a" ).attr( "href" );
Working with Selections
Getters & Setters
// The .html() method sets all the h1 elements' html to be "hello world"
$( "h1" ).html( "hello world" )
// The .html() method returns the html of the first h1 element
$( "h1" ).html();
// > "hello world"
Text
Chaining
Text
$( "#content" )
.find( "h3" )
.eq( 2 )
.html( "new text for the third h3!" );
jQuery also provides the .end() method to get back to the original selection should you change the selection in the middle of a chain:
$( "#content" )
.find( "h3" )
.eq( 2 )
.html( "new text for the third h3!" )
.end() // Restores the selection to all h3s in #content
.eq( 0 )
.html( "new text for the first h3!" );
Manipulating Elements
Text
.html() // Get or set the HTML contents.
.text() // Get or set the text contents; HTML will be stripped.
.attr() // Get or set the value of the provided attribute.
.width() // Get or set the width in pixels of the first element
in the selection as an integer.
.height() // Get or set the height in pixels of the first element
in the selection as an integer.
.position() // Get an object with position information for the first
element in the selection, relative to its
first positioned ancestor. This is a getter only.
.val() // Get or set the value of form elements.
.insertAfter()
.after()
.insertBefore()
.before()
.appendTo()
.append()
.prepend()
.remove()
Text
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$( "<p>Test</p>" ).insertAfter( ".inner" );
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
<p>Test</p>
</div>
.insertAfter()
.after()
$( ".inner" ).after( "<p>Test</p>" );
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">Goodbye</div>
<p>Test</p>
</div>
Creating New Elements
// Getting a new element on to the page.
var myNewElement = $( "<p>New element</p>" );
myNewElement.appendTo( "#content" );
// Creating and adding an element to the page at the same time.
$( "ul" ).append( "<li>list item</li>" );
or
<div class="container">
<h2>Greetings</h2>
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
$( ".inner" ).append( "<p>Test</p>" );
<h2>Greetings</h2>
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
.append()
Text
Moving Elements
// Changing the HTML of an element.
$( "#myDiv" ).html( "New <strong>first</strong> paragraph!" );
// Moving elements using different approaches.
// Make the first list item the last list item:
var li = $( "#myList li:first" ).appendTo( "#myList" );
// Another approach to the same problem:
$( "#myList" ).append( $( "#myList li:first" ) );
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
$( ".hello" ).remove();
<div class="container">
<div class="goodbye">Goodbye</div>
</div>
Removing elements
CSS, Styling, & Dimensions
// Setting CSS properties.
$( "h1" ).css( "fontSize", "100px" ); // Setting an individual property.
// Setting multiple properties.
$( "h1" ).css({
fontSize: "100px",
color: "red"
});
Using CSS Classes for Styling
// Working with classes.
var h1 = $( "h1" );
h1.addClass( "big" );
h1.removeClass( "big" );
h1.toggleClass( "big" );
if ( h1.hasClass( "big" ) ) {
...
}
CSS, Styling, & Dimensions
Dimensions
// Basic dimensions methods.
// Sets the width of all <h1> elements.
$( "h1" ).width( "50px" );
// Gets the width of the first <h1> element.
$( "h1" ).width();
// Sets the height of all <h1> elements.
$( "h1" ).height( "50px" );
// Gets the height of the first <h1> element.
$( "h1" ).height();
// Returns an object containing position information for
// the first <h1> relative to its "offset (positioned) parent".
$( "h1" ).position();
Data Methods
// Storing and retrieving data related to an element.
$( "#myDiv" ).data( "keyName", { foo: "bar" } );
$( "#myDiv" ).data( "keyName" ); // Returns { foo: "bar" }
Utility Methods
$.each()
$.each([ "foo", "bar", "baz" ], function( index, value ) {
console.log( "element " + index + " is " + value );
});
$.inArray()
var myArray = [ 1, 2, 3, 5 ];
if ( $.inArray( 3, myArray ) !== -1 ) {
console.log( "found it!" );
}
$.extend()
var firstObject = { foo: "bar", a: "b" };
var secondObject = { foo: "baz" };
var newObject = $.extend( firstObject, secondObject );
console.log( firstObject.foo ); // "baz"
console.log( newObject.foo ); // "baz"
console.log( newObject.foo ); // {foo: "baz", a: "b"}
Utility Methods
Testing Type
$.isArray([]); // true
$.isFunction(function() {}); // true
$.isNumeric(3.14); // true
$.type( true ); // "boolean"
$.type( 3 ); // "number"
$.type( "test" ); // "string"
$.type( function() {} ); // "function"
$.type( new Boolean() ); // "boolean"
$.type( new Number(3) ); // "number"
$.type( new String('test') ); // "string"
$.type( new Function() ); // "function"
$.type( [] ); // "array"
$.type( null ); // "null"
$.type( /test/ ); // "regexp"
$.type( new Date() ); // "date"
Using jQuery’s .index() Function
<ul>
<div class="test"></div>
<li id="foo1">foo</li>
<li id="bar1" class="test">bar</li>
<li id="baz1">baz</li>
<div class="test"></div>
</ul>
<div id="last"></div>
.index() with a jQuery Object Argument
var foo = $( "li" );
var baz = $( "#baz1" );
console.log( "Index: " + foo.index( baz ) ); // 2
var tests = $( ".test" );
var bar = $( "#bar1" );
// Implicitly calls .first() on the argument.
console.log( "Index: " + tests.index( bar ) ); // 1
console.log( "Index: " + tests.index( bar.first() ) ); // 1
Links
https://jquery.com/browser-support/
http://anton.shevchuk.name/javascript/jquery-for-beginners/
book
http://anton.shevchuk.name/jquery-book/
video
http://loftblog.ru/material/osnovy-jquery-vvedenie-v-jquery/
Tutorial
http://www.w3schools.com/jquery/
https://www.codeschool.com/courses/try-jquery
https://www.codecademy.com/learn/jquery
Questions?
Home Work
Home Work
1 Сверстать форму согласно дизайна
2 Вывести данные полученный по api (/api/products) или с json файла
3 Вывести ошибку если запрос fail ("Services unavailable")
4 Удаление продуката при клике на "x".
- При клике на "x" вывести popup с подверждением удаления
5 При апдейте pQuantity должна менятся Total цена
6 Валидация
6.1 При update QTY валидируем данный продукт
6.2 При buy валидируем наличия товара с сервера.
6.3 Валидация на целые чисел для QTY
6.4 Максимальное QTY для каждого товара которое можем купить:
- Если Sum = Stock + Sklad >= 99 То можем купить максимум 99.
- Если Sum = Stock + Sklad <= 99 То можем купить значение равное Sum
- Если флаг isInStoreOnly = true То можем купить товар только с магазина
- Если Stock + Sklad = 0 то вывод соответсвующего сообщения
6.5 Вывод ошибок:
"Services unavailable"
"The product out of stock" если продукт отсутствует на магазине и складе
"Sorry, the maximum quantity you can order is 'n'". где 'n' - количество items
7 При успешной покупке вывести сообщение что продукты куплены
1 download project https://github.com/RovenskyOleg/jQueryTask
2 download https://nodejs.org/en/ 4 version and install
3 go to project folder (D:\jqueryTask>)
4 in console run command
"npm install" (if use ubuntu or mac "sudo npm install")
5 run server in the project directory
"node server.js"
6 go to http://localhost:8080/
Start work
Basic jQuery Core
By Oleg Rovenskyi
Basic jQuery Core
jQuery Core
- 754