So I’m building a little set of Markdown helpers for an ActiveAdmin Form. I just have the italics one so far.
#form.html.erb
# ... some form code
<%= link_to "i", "#", :class => "btn", :id => "italics_button" %>
<%= f.input :body %>
# ... rest of form omitted
Which gives me the button with an ID of “italics_button” and a textarea with an ID of post_body. So far, all is well.
Now I have a coffeescript file to handle the wrapping the selected text in a given tag.
#posts.js.coffee
wrapText = (elementID, openTag, closeTag) ->
textArea = $("##{elementID}") #select the text area
len = textArea.val().length #total length of the text area
start = textArea[0].selectionStart # start of the selected text
end = textArea[0].selectionEnd # end of the selected text
selectedText = textArea.val().substring(start, end) # The selected Text
replacement = openTag + selectedText + closeTag # string with the selected text wrapped in the bbcode
textArea.val(textArea.val().substring(0,start) + replacement + textArea.val().substring(end, len)) # perform the replacement
$('#italics_button').click (event) ->
event.preventDefault()
wrapText('post_body', '*', '*')
I’m fairly confident this code is okay, because I ripped it out of a project from a couple months ago where I did the same thing on a normal non-AA form.
I’ve updated the initializer to bring in the custom javascript:
# active_admin.rb
# rest of file omitted
config.register_javascript 'posts.js.coffee'
And finally, I can see on the New Post page in Active Admin, the javascript file is included and compiled.
However, the javascript event does not appear to be called. When I click #italics_button, the page attempts to follow the link to “#” and the javascript does not run.
This will be executed as soon as the browser sees it:
Your CoffeeScript will probably be loaded in the page’s
<head>element so there probably won’t be any#italics_buttonin the DOM when you$('#italics_button').click(...)so no callback will be bound.You can try the usual “run when the document is ready approach”:
or you could use a “live” handler:
The latter will be useful if the
#italics_buttonwill be added dynamically after the server has sent the page to the browser.