SlideShare a Scribd company logo
jQuery in Rails
          Louie Zhao
            Co - Founder

 Caibangzi.com & IN-SRC Studio




                 1
Problem

• JavaScript programming can be hard
 • Completely dynamic language
 • JavaScript, by itself, isn’t useful

                     2
3
JavaScript Library


• Drastically simplify DOM, Ajax, Animation


                     4
5
jQuery


• An open source JavaScript library that
  simplifies the interaction between HTML
  and JavaScript.




                     6
twitter.com       time.com    microsoft.com




amazon.com      wordpress.com      ibm.com




                      7
8
jQuery

• Cross Browser
• Small
• Lean API, fun coding

                     9
jQuery Overview

• Selector & Chaining
• DOM manipulation
• Events
• Effects
• Ajax
                    10
Selector & Chaining

$(selector).method1().method2().method3();




     $('#goAway').hide().addClass('incognito');




                         11
Selector

• Basic CSS selectors
• Positional selectors
• Custom jQuery selectors

                   12
Basic CSS Selector


   $('li>p')




        13
Basic CSS Selector


$('div.someClass')




        14
Basic CSS Selector


$('#testButton')




        15
Basic CSS Selector


 $('img[alt]')




        16
Basic CSS Selector


$('a[href$=.pdf]')




        17
Basic CSS Selector


$('button[id*=test]')




          18
Positional Selectors


   $('p:first')




         19
Positional Selectors


$('img[src$=.png]:first')




             20
Positional Selectors


$('button.small:last')




           21
Positional Selectors


$('li:first-child')




         22
Positional Selectors


$('a:only-child')




         23
Positional Selectors

$('li:nth-child(2)')
$('li:nth-child(odd)')
$('li:nth-child(5n)')
$('li:nth-child(5n+1)')

           24
Positional Selectors

$('.someClass:eq(1)')
$('.someClass:gt(1)')
$('.someClass:lt(4)')



           25
Custom Selectors
$(':button:hidden')
$('input[name=myRadioGroup]:radio:checked')
$(':text:disabled')
$('#xyz p :header')
$('option:not(:selected)')
$('#myForm button:not(.someClass)')
$('select[name=choices] :selected')
$('p:contains(coffee)')



                     26
Add / Remove

 $('div').css('font-weight','bold').add('p').css('color','red');

$('body *').css('font-weight','bold').not('p').css('color','red');




                                27
Find / Slicing

$('div').css('background-color','blue').find('img').css
('border','1px solid aqua');




            $('body *').slice(2,3).hide();




                          28
Matching by
    Relationship

.parents("tr:first")




         29
Map

var values = $('#myForm :input').map(function(){
  return $(this).val();
});




                       30
Controlling Chaining

$('div').add('p').css('color','red').end().hide();




$('div').css('background-color','yellow').children
('img').css('border','4px ridge maroon').andSelf
().css('margin','4em');




                         31
DOM Manipulation
• Changing contents
      .html("<p>This is a paragraph.</p>")

      .text("<p>This is a paragraph.</p>")




                       32
DOM Manipulation

• Inserting inside
 • append(content)
 • appendTo(selector)
 • prepend(content)
 • prependTo(selector)
                   33
DOM Manipulation

• Inserting outside
 • after(content)
 • insertAfter(selector)
 • before(content)
 • insertBefore(selector)
                    34
DOM Manipulation

• Inserting around
• Replacing
• Removing
• Copying

                     35
Events

• Page Load
• Event Handling
• Live Events
• Event Helpers

                   36
Events
• Run after DOM, but before images
   $(document).ready(function() {});




                    37
Effects




   38
Ajax
• Cross browser
              $.ajax();

              $.load();

              $.get();

              $.post();


                   39
jQuery UI


• Interactions
• Widgets


                 40
Interactions

• Draggable
• Droppable
• Resizable
• Selectable
• Sortable
               41
Widgets
• Accordion
• Date picker
• Dialog
• Progress Bar
• Slider
• Tabs
                 42
Prototype - Controller

class BooksController < ApplicationController
  def create
    @book = Book.create!(params[:book])
    respond_to do |format|
      format.html { redirect_to books_path }
      format.js
    end
  end
end




                         43
Prototype - View
<!-- layouts/application.rhtml -->
<%= javascript_include_tag :defaults %>

<!-- layouts/show.rhtml -->
<% form_remote_for :book, :url => books_path %>
    ....
<% end %>

<!-- app/views/books/create.js.rjs -->
page.insert_html :bottom, :books, :partial => 'book'




                         44
jQuery - View
<!-- layouts/application.rhtml -->
<%= javascript_include_tag 'jquery', 'jquery-ui',
'application' %>

<!-- public/javascripts/applicaton.js -->
$(document).ready(function() {
  $("#new_book").submit(function() {
    $.post($(this).attr("action"), $(this).serialize(),
null, "script")
    return false;
  });
});

<!-- app/views/books/create.js.erb -->
$("#books").append("<%= escape_javascript(render
(:partial => @book)) %>");

                           45
jQuery - View
jQuery.fn.submitWithAjax = function() {
   this.submit(function() {
     $.post($(this).attr("action"), $(this).serialize(), null,
"script")
     return false;
   });
};

$(document).ready(function() {
  $("#new_book").submitWithAjax();
});




                               46
delete
<tr id="book_<%= book.id %>">
  <td><%= h book.title %></td>
  <td><%= h book.author %></td>
  <td><%= book.price %></td>
  <td><%= book.published_on.to_s %></td>
  <td><%= link_to 'X', book_path(book), :method => :delete %></td>
</tr>




class BooksController < ApplicationController
  def destroy
    @book = Book.find params[:id]
    @book.destroy
    redirect_to books_path
  end
end




                                        47
delete
<td>
  <%= link_to 'X', book_path(book), :class => "delete" %>
</td>



       $(document).ready(function() {
         $("a.delete").click(function(){
           $.ajax({
             type: "DELETE",
             url: this.href
           });
           $(this).parents("tr:first").remove();
           return false;
         });
       });
                            48
Date Picker

$("#book_published_on").datepicker();




                  49
Ajax Pagination
class BooksController < ApplicationController
  def index
    @books = Book.all.paginate :per_page => 1,
                               :page => params[:page]
  end
end

<h2>Book List</h2>
<%= will_paginate @books %>
<table>
  <tbody id="books">
    <%= render :partial => 'book', :collection => @books %>
  </tbody>
</table>
<%= will_paginate @books %>

                             50
Ajax Pagination
       <h2>Book List</h2>
       <div id="paginated_books">
       <%= render :partial => 'books' %>
       </div>



<%= will_paginate @books %>
<table>
  <tbody id="books">
    <%= render :partial => 'book', :collection => @books %>
  </tbody>
</table>
<%= will_paginate @books %>



                             51
Ajax Pagination
index.js.erb
$("#paginated_books").html("<%= escape_javascript(render('books')) %>")




application.js
$(document).ready(function() {
  $(".pagination a").live("click", function() {          .click(function() ...
    $(".pagination").html("loading....");            .live(“click”, function() ...
    $.get(this.href, null, null, "script");
    return false;
  });
});


                                        52
Thanks!



   53

More Related Content

KEY
JQuery In Rails
PDF
PhoneGap: Local Storage
PPT
Kick start with j query
PDF
DOM Scripting Toolkit - jQuery
KEY
Advanced jQuery
PPTX
jQuery Presentasion
PDF
Юрий Буянов «Squeryl — ORM с человеческим лицом»
PPTX
jQuery
JQuery In Rails
PhoneGap: Local Storage
Kick start with j query
DOM Scripting Toolkit - jQuery
Advanced jQuery
jQuery Presentasion
Юрий Буянов «Squeryl — ORM с человеческим лицом»
jQuery

What's hot (20)

PDF
Learning jQuery in 30 minutes
PPTX
jQuery Fundamentals
PDF
Prototype & jQuery
KEY
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
PPT
A Short Introduction To jQuery
ODP
Introduction to jQuery
PDF
Write Less Do More
PDF
JQuery UI
PPTX
Taming that client side mess with Backbone.js
PDF
jQuery and Rails, Sitting in a Tree
PDF
Using jQuery to Extend CSS
PDF
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
PPT
JQuery introduction
PPT
PDF
jQuery Essentials
PDF
jQuery Essentials
PDF
jQuery in 15 minutes
PPTX
Jquery-overview
PDF
Crowdsourcing with Django
Learning jQuery in 30 minutes
jQuery Fundamentals
Prototype & jQuery
Building Single Page Apps with Backbone.js, Coffeescript and Rails 3.1
A Short Introduction To jQuery
Introduction to jQuery
Write Less Do More
JQuery UI
Taming that client side mess with Backbone.js
jQuery and Rails, Sitting in a Tree
Using jQuery to Extend CSS
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
JQuery introduction
jQuery Essentials
jQuery Essentials
jQuery in 15 minutes
Jquery-overview
Crowdsourcing with Django
Ad

Viewers also liked (8)

PDF
A~Z Of Accelerator
PDF
Hong Qiangning in QConBeijing
PPTX
Rails + JCR
PPT
Accelerator Workshop "After"
KEY
Using Sinatra as a lightweight web service
PDF
Rack
ODP
Legal contracts 2.0
PDF
Rails Metal, Rack, and Sinatra
A~Z Of Accelerator
Hong Qiangning in QConBeijing
Rails + JCR
Accelerator Workshop "After"
Using Sinatra as a lightweight web service
Rack
Legal contracts 2.0
Rails Metal, Rack, and Sinatra
Ad

Similar to Jquery In Rails (20)

PDF
PPTX
jQuery Foot-Gun Features
PPTX
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
PPT
J query
PPTX
Jquery Complete Presentation along with Javascript Basics
PDF
Web2.0 with jQuery in English
PDF
jQuery Rescue Adventure
PDF
Introduzione JQuery
PPTX
Jquery
PDF
jQuery for beginners
PPTX
Jquery fundamentals
PDF
Introduction to jQuery (Ajax Exp 2006)
PDF
Jquery in-15-minutes1421
PDF
Introduction to jQuery (Ajax Exp 2007)
ZIP
Django at the Disco
ZIP
Django at the Disco
ZIP
Django at the Disco
ZIP
Django at the Disco
PDF
Django at the Disco
PPT
JQuery Flot
jQuery Foot-Gun Features
How I Learned to Stop Worrying and Love jQuery (Jan 2013)
J query
Jquery Complete Presentation along with Javascript Basics
Web2.0 with jQuery in English
jQuery Rescue Adventure
Introduzione JQuery
Jquery
jQuery for beginners
Jquery fundamentals
Introduction to jQuery (Ajax Exp 2006)
Jquery in-15-minutes1421
Introduction to jQuery (Ajax Exp 2007)
Django at the Disco
Django at the Disco
Django at the Disco
Django at the Disco
Django at the Disco
JQuery Flot

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Electronic commerce courselecture one. Pdf
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
Machine Learning_overview_presentation.pptx
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
cuic standard and advanced reporting.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Unlocking AI with Model Context Protocol (MCP)
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Reach Out and Touch Someone: Haptics and Empathic Computing
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Electronic commerce courselecture one. Pdf
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Group 1 Presentation -Planning and Decision Making .pptx
Machine Learning_overview_presentation.pptx
SOPHOS-XG Firewall Administrator PPT.pptx
Machine learning based COVID-19 study performance prediction
cuic standard and advanced reporting.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
Building Integrated photovoltaic BIPV_UPV.pdf
Spectroscopy.pptx food analysis technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton

Jquery In Rails