jQuery – write less do more – What is jQuery



jQuery – write less do more – What is jQuery

0 0


jquery-talk


On Github andrei-yanovich / jquery-talk

jQuery

write less do more

Created by Andrei Yanovich

What is jQuery

“jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use”

Why use it?

  • Succinct API
    $('div[name^=andrei]').addClass('presenter')
  • Crossbrowser support
  • Mature
    • More then 30% of all sites that use javascript use jQuery
    • Rich documentation and Tutorials
    • Ton of plugins
  • You can learn it in half an hour!
Лаконичный API, кроссбраузерность (упомянуть 2 версию)

Statistics for websites using JavaScript technologies

Используется практически повсеместно

3 easy steps to get started

Get the latest version

Reference it in your code

Start using on 'document ready' event:

$(document).ready(function() {
	...
});

or simply

$(function () {

});

$() function

jQuery can be invoked using $() or jQuery(). jQuery.noConflict() will revert $ to prev value

New DOM elements can be created on the fly:

$('<span id="newSpan">NEW!</span>').appendTo('.createdom.placeholder')
Run

Elements can be selected:

$('#newSpan'), $('.class'), ...

and manipulated:

$('#newSpan').hide(), $('#newSpan').css('background-color', 'green')
magic $('#newSpan').fadeToggle('slow')

Chainability

Most of the jQuery API funtions return the jQuery object. This allows for a fluent, compact programming model.

$('div').show().toggleClass('main').html('hello');

$.get('example.url') 
 .done(function() { alert("success"); }) 			
 .fail(function() { alert("error"); }) 				
 .always(function() { alert("complete"); });

Some methods return a different elements collection. You can call .end() to revert to the previous collection

$('#intro').css('color', '#cccccc')
	.find('a').addClass('highlighted').end
	.find('span').css('color', 'red').end

Selectors

Basic selectors

$('*') /select everything/

$('div') /by tag name/

$('#id') /by id/

$('.class') /by class/

$('div.class, h1, h2') /multiple combinations/

Hierarchy selectors

$('table td') /descendants/

$('tr > td') /children/

$('label + input') /adjacent siblings/

$('#content ~ div') /general siblings/

$('.slides section:first h1 ~ *') $('h1 + h3') $('.slides section') $('.slides > section')

Index selectors

$('a:first') /first element/

$('a:last') /last element/

$('a:lt(2)') /index less than/

$('a:eq(2)') /index equeals/

Attribute selectors

$('div[id]') /has id/

$('div[id="main"]') /with id = name/

$('div[name^="main"]') /name starts with main/

$('div[name$="main"]') /name ends with main/

$('div[name*="main"]') /name contains main/

Form selectors

$(':checkbox') /checkboxes/

$(':radio') /radio buttons/

$(':button') /buttons/

$(':text') /text input/

$(':checked') /checked/

$(':selected') /selected/

$(':enabled') /enabled/

$(':disabled') /disabled/

Other magic selectors

$('div:visible') /visible element/

$('div:hidden') /hidden element/

$(':animated') /animated/

See others https://api.jquery.com/category/selectors/

jQuery collections

Selector returns a jQuery collection

You can treat it like an array

$('div.section').length equals to $('div.section').size()
$('div.section')[0]
$('div.section').each(function(i) {
	console.log('Item' + i + ' is ', this)
})

Traversing the DOM

jQuery provides additional methods for traversing the DOM

$('div.section').parent()

$('div.section').next()

$('div.section').prev()

$('div.section').nextAll('div')

$('div.section').parents()

$('div.section').find('h1')

DOM manipulation

Modifying the content

Getting and setting inner content

$('.placeholder').html('<p>Hello</p>');

Replacing elements

$('.placeholder').replaceWith('<div>Hello</div>');
$('<h2>Hello</h2>').replaceAll('h1');

Remove all children

$('#main').empty();

Remove selection

$('.main').remove();

Change position

$('#nav').appendTo('#main');

Handling Attributes

/* get single attribute */
$('img').attr('alt');

/* set single attribute  */
$('img').attr('alt', 'img.description');

/* remove attribute */
$(':text').removeAttr('required');

/* set multiple attributes */
$('img').attr({ width : 10, height: 10 });

Handling CSS

/* get style */
$('div').css('float');

/* set style  */
$('div').css('float', 'left');

/* set multiple styles */
$('div').css({ position : 'relative', float: 'none' });

/* add/remove css class */
$('div').addClass('main');
$('div').removeClass('main');
$('div').toggleClass('main');

Grabbing values

Some methods return results from the first matched element

var height = $('div#intro').height();
var src = $('img.photo').attr('src');
var lastP = $('p:last').html()
var hasFoo = $('p').hasClass('foo');
var email = $('input#email').val();

Handling events

.BIND() Attach a handler to an event for the elements. .bind( eventType [, eventData ], handler(eventObject) )

$( "#foo" ).bind( "click", function() {
  alert( "User clicked on 'foo.'" );
});

.UNBIND() Remove a previously-attached event handler from the elements.

//Removes the handlers regardless of type.
$( "#foo" ).unbind();

//Removing handlers for click event type
$( "#foo").unbind( "click" );

Bind migth be deprecated

Handling events

.ON() a proper val to attach an event handler

function myHandler( event ) {
  alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );

.ONE() Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

.OFF() Remove an event handler.

$( "p" ).off();

//Remove all delegated click handlers from all paragraphs:
$( "p" ).off( "click", "**" );

// ... Foo will no longer be called.
$( "body" ).off( "click", "p", foo );

Tell about event object

Shortcuts

.change()
.focus()
.focusin()
.select()
.submit()
.click()
.dblclick()
.mouseenter()
.mouseleave()
.mousemove()
.keydown()
.keypress()
.keyup()
etc...

Animation

  • jQuery has buil in effects:
    $('h1').hide('slow');
    $('h1').slideDown('fast');
    $('h1').fadeOut(2000);
  • You can chain them:
    $('h1').fadeOut(1000).slideDown()
  • Or make your own:
    $('#block').animate({
    	width: '+=60px',
    	opacity: 0.4,
    	fontSize: '3em',
    	borderWidth: '10px'
    }, 1500);

Plugins

jQuery is extensible through plugins, which can add new methods to the jQuery object:

  • Form: better form manipulation
  • UI: drag and drop and widgets
  • ... dozens more
jQuery.fn.hideLinks = function() {
	return this.find('a[href]').hide().end();
}
$('p').hideLinks();

Further reading

  • http://jquery.com/
  • http://docs.jquery.com/
  • https://jqueryui.com/

Questions?

jQuery write less do more Created by Andrei Yanovich