Quantcast
Channel: michael f1337 » code
Viewing all articles
Browse latest Browse all 9

Easy Unobtrusive JavaScript with jQuery and Rails

$
0
0

Using 5 (logical) lines of code

app/views/layouts/rockets.html.erb:
<head>
    ...
    <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' %>
    ...
</head>
app/views/rockets/index.html.erb:
<%= link_to('', edit_rockets_path(@rocket), :class => 'edit', :title => 'Editing Rocket') %>
public/javascripts/application.js:
// when the dom is ready to be manipulated
$(document).ready(function ()
{
    // for every <a class="edit"></a>
    $('a.edit').each(function (i)
    {
        // make the empty anchor visible by adding some text
        // <a class="edit">edit</a>
        $(elem).html('edit');
    });
});


Easy. :)

A little fancier, still under 20 (logical) lines of code

For this example, download Shadowbox, and move it to public/shadowbox.

app/views/layouts/rockets.html.erb:
<head>
    ...
    <%= javascript_include_tag 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' %>
    <%= stylesheet_link_tag '/shadowbox/shadowbox.css' %>
    <%= javascript_include_tag '/shadowbox/shadowbox.js' %>
    ...
</head>
app/views/rockets/index.html.erb:
<%= link_to('', edit_rockets_path(@rocket), :class => 'edit', :title => 'Editing Rocket') %>
public/javascripts/application.js:
// initialize Shadowbox
Shadowbox.init({
    players:    [ 'iframe' ]
});

// when the dom is ready to be manipulated
$(document).ready(function ()
{
    // for every <a class="edit"></a>
    $('a.edit').each(function (i)
    {
        // make the empty anchor visible by adding some text
        // <a class="edit">edit</a>
        $(elem).html('edit');

        // when the anchor is clicked
        $(elem).click(function ()
        {
            // open Shadowbox
            Shadowbox.open({
                // load the anchor's href in an iframe
                content:    $(this).attr('href'),
                player:     'iframe',
                // set Shadowbox caption to anchor's title property
                title:      $(this).attr('title')
            });
            // stop the browser from redirecting
            // to the href page (it's in the iframe already)
            return false;
        });
    });
});

Viewing all articles
Browse latest Browse all 9

Trending Articles