15 Clickable Notes JavaScript - getfretless/elevennote GitHub Wiki
Create a new JavaScript file called notes.js
. We'll write a few lines of JavaScript to make the notes list in the sidebar clickable.
In JavaScript, we pass anonymous functions as arguments to other functions quite a bit. In JavaScript, these anonymous functions are closures, meaning that they have bindings to the context in which they are called. Blocks, Procs, and Lambdas in Ruby are also implemented as closures, and are more-or-less analygous to their JavaScript cousins.
We can wrap the document
object in a jQuery function, turning it into a jQuery object on which we can call ready
. The ready
function takes an anonymous function (a closure) as an argument, specifying code that is to be run when the document is finished rendering.
$(document).ready(function() {
/* code to be run once document is rendered */
});
In this case, we want to handle any click events that occur on list items that are children of the #notes
element. Our event handler should 1) prevent any default behavior from occurring when the element is clicked, and 2) navigate to note's show
page.
JavaScript is unaware of Rails routing. Rather than hardcoding the page_path
within JavaScript, let's add the path as a data attribute to the list items.
_app/views/notes/list.html.erb
<% if @notes.present? %>
<ul id="notes">
<% @notes.each do |note| %>
<li data-url="<%= note_url(note) %>">
<%= content_tag :div, note.title, class: 'note-title' %>
<%= content_tag :div, note.body_html.to_s.html_safe, class: 'note-body' %>
</li>
<% end %>
</ul>
<% end %>
That way we can grab the value of the data attribute within our closure. OK, we have what we need to write our JavaScript.
app/assets/javascripts/notes.js
$(document).ready(function() {
$('#notes > li').click(function(ev) {
ev.preventDefault();
location.href = $(this).data('url');
});
});
jQuery actually allows us to skip one function call by passing our closure directly to the $
function. Doing so has the same effect as passing it to $(document).ready
.
app/assets/javascripts/notes.js
$(function() {
$('#notes > li').click(function(ev) {
ev.preventDefault();
location.href = $(this).data('url');
});
});
Are your sidebar links clickable now? Commit!