jquery

23
JQuery, Ajax and Rails Nicola Sheldrick d:evolute July 13, 2012

Upload: devolute

Post on 26-Oct-2014

110 views

Category:

Documents


2 download

DESCRIPTION

Introduction into jQuery

TRANSCRIPT

Page 1: jQuery

JQuery, Ajax and Rails

Nicola Sheldrick

d:evolute

July 13, 2012

Page 2: jQuery

JQuery, Ajax and Rails

Nicola Sheldrick

d:evolute

July 13, 2012

Page 3: jQuery

1 jQuery Intro

2 Ajax

3 Ajax and JQuery

Page 4: jQuery

jQuery intro

Lightweight library, namespaced behind the jQuery variable, whichis aliased with a dollar sign ($)

jQuery doesn’t extend any native JavaScript objects

Focused on queries

All of jQuery’s instance methods are performed on selectors,instead of interating over elements, use a selector to collect them

obtaining jQueryinclude it with a <script> tag

%script{:src ⇒ "jquery-1.7.2.min.js"}or use a CDN

= javascript include tag

"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"

⇒ jQuery is the new default JavaScript library in Rails 3.1

4 / 20

Page 5: jQuery

jQuery intro

Lightweight library, namespaced behind the jQuery variable, whichis aliased with a dollar sign ($)

jQuery doesn’t extend any native JavaScript objects

Focused on queries

All of jQuery’s instance methods are performed on selectors,instead of interating over elements, use a selector to collect them

obtaining jQueryinclude it with a <script> tag

%script{:src ⇒ "jquery-1.7.2.min.js"}or use a CDN

= javascript include tag

"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"

⇒ jQuery is the new default JavaScript library in Rails 3.1

4 / 20

Page 6: jQuery

jQuery intro

Lightweight library, namespaced behind the jQuery variable, whichis aliased with a dollar sign ($)

jQuery doesn’t extend any native JavaScript objects

Focused on queries

All of jQuery’s instance methods are performed on selectors,instead of interating over elements, use a selector to collect them

obtaining jQueryinclude it with a <script> tag

%script{:src ⇒ "jquery-1.7.2.min.js"}or use a CDN

= javascript include tag

"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"

⇒ jQuery is the new default JavaScript library in Rails 3.1

4 / 20

Page 7: jQuery

JavaScript vs jQuery example

// JavaScript example

var elements = document.getElementByClassName(’foo’);

for (var i=0; i < elements.length; i++) {

elements[i]. className += " selected";

}

// jQuery example

$.(".foo").addClass("selected");

5 / 20

Page 8: jQuery

JavaScript vs jQuery example

// JavaScript example

var elements = document.getElementByClassName(’foo’);

for (var i=0; i < elements.length; i++) {

elements[i]. className += " selected";

}

// jQuery example

$.(".foo").addClass("selected");

5 / 20

Page 9: jQuery

jQuery Basics

Single global function named jQuery()

Factory function rather than a constructor

Returns a newly created object, without using the new keyword

Method-chaining

Most common operations are getting and setting the value of:

1 HTML attributes2 CSS styles3 Element content4 Element geometry

Single method for getter and setter

6 / 20

Page 10: jQuery

Getting and Setting

HTML attributes

// Set the src attribute of element with id

icon

$.("#icon").attr("src", "icon.png");

CSS attributes

// Increase all <h1> font sizes by 25%

$.("h1").css("font -size", function(i, curval)

{

return Math.round (1.25* parseInt(curval));

});

CSS classes addClass(), removeClass(), toggleClass()

7 / 20

Page 11: jQuery

Inserting and Replacing Elements

Operation $(target) $(content).method(content) .method(target)

content at end of target append() appendTo()

content at start of target prepend() prependTo()

content after target after() insertAfter()

content before target before() insertBefore()

replace target with content replaceWith() replaceAll()

8 / 20

Page 12: jQuery

Ajax

Asynchronous JavaScript and XML

Can call the web server without refreshing the entire page

Implemented with XMLHttpRequest

Send data directly to the web serverResponse loaded directly into serverJson commonly used instead of XML

9 / 20

Page 13: jQuery

JavaScript in Rails

app/assets/javascripts/application.js is loaded with every page

All other JavaScript files must be explicitly loaded unless addedJavaScript default pages in config/application.rb

JavaScript to be executed will be a function wrapped in the jQuery$(document).ready( ) event

10 / 20

Page 14: jQuery

Ajax in Rails

Implemented with unobtrusive JavaScript using custom attributes

data-method Http method call (put, get, delete, or post)

data-confirm Confirmation dialog before proceding

data-remote Submit via Ajax if true

data-disable-with disable form elements during submission

11 / 20

Page 15: jQuery

Form

Add remote ⇒ true, to link or submit button to execute using ajax

= link_to "Delete", post , :confirm => "Are you sure?",

:method => :delete , :remote => true ,

:class => ’delete_post ’

12 / 20

Page 16: jQuery

Controller and Views

JavaScript will be sent to the client to be executed

Need to respond to JavaScript in a similar manner to html,format.js

View file will contain JavaScript to be executed on the client

create.js.erb or destroy.js.erb

13 / 20

Page 17: jQuery

Controller

respond_to do |format|

if @project.save

format.html { redirect_to ’/’, :notice => "Project

was successfully created")}

format.xml { render :xml => @project , :status => :

created , :location => @project }

format.js { @result = "good"}

else

format.html { render :action => "new" }

format.xml { render :xml => @project.errors , :status

=> :unprocessaple_entity }

format.js { @result = "bad" }

end

end

14 / 20

Page 18: jQuery

Ajax and JQuery

Ajax support built into JQuery

good when a lot of funtionality is on the client

does not support unobtrusive JavaScript

15 / 20

Page 19: jQuery

$.ajax

The jQuery function upon which all Ajax calls are built

$.ajax(<url>, <settings>)url: the URL to callsettings: JSON object containing settings suchas:

HTTP callfunction to call if successful

16 / 20

Page 20: jQuery

$.ajax Example

$.ajax ( ’/projects /8’, {

type: ’Delete ’,

success: function(data) {

alert ( ’Project deleted ’);

});

17 / 20

Page 21: jQuery

additional Ajax methods

$.post(<url>, <data>, <success function>)

$.post ( ’/projects/’, params , function () {

alert ( ’successful ’);

});

$.get(<url>, <data>, <success function>)

$.get ( ’/projects /1’, function(data) {

$(’tr’).val(data);

});

18 / 20

Page 22: jQuery

Unobtrusive Javascript

Separation of functionality (the ”behaviour layer”) from a Webpage’s structure/content and presentation

Best practices to avoid the problems of traditional JavaScriptprogramming (such as browser inconsistencies and lack ofscalability)

All Javascript code in external filesthe site works with or without Javascript

HTML should be just as accessible to those with disabilities ordevices that don’t support Javascript

19 / 20

Page 23: jQuery

Unobtrusive JavaScript Issues

Need to design site for use with or without JavaScript

Doesn’t work with sites where JavaScript is integral to properfunction

Biggest benefit is for designing sites for people with disabilities⇒ mobile devices starting to have some form of JavaScript support

20 / 20