#205 Unobtrusive Javascript
Keep JavaScript out of your HTML content with unobtrusive JavaScript. Here I show how Rails 3 works with this best practice.
- Download:
- source code Project Files in Zip (163 KB)
- mp4 Full Size H.264 Video (18.8 MB)
- m4v Smaller H.264 Video (13.4 MB)
- webm Full Size VP8 Video (35 MB)
- ogv Full Size Theora Video (25.6 MB)
Browse_code
Browse Source Code
Resources
- Episode 37: Simple Search Form
- Episode 77: Destroying Without JavaScript
- prototype_legacy_helper
- jquery-ujs
- Full episode source code
ujs_example.html
<!DOCTYPE html> <html> <head> <title>UJS Example</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript" charset="utf-8"> $(function() { $("#alert").click(function() { alert(this.getAttribute("data-message")); return false; }) }) </script> </head> <body> <h1><a href="#" id="alert" data-message="Hello UJS!">Click Here</a></h1> </body> </html>
layouts/application.html.erb
<%= javascript_include_tag :defaults %> <!-- or --> <%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "jquery.rails.js" %> <%= csrf_meta_tag %>
products/index.html.erb
<% form_tag products_path, :method => :get, :remote => true do %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %> </p> <% end %> <div id="products"> <%= render @products %> </div>
products/index.js.erb
$("products").update("<%= escape_javascript(render(@products)) %>"); // or $("#products").html("<%= escape_javascript(render(@products)) %>");
loading