2

I know this question is beaten to death on SO but I tried all possible approaches but nothing seems to work for me. I am trying to add a simple alert when a link is clicked. Appreciate your inputs on this.

All it does

View partial: (I am want to fire some coffeescript on click of the Cancel link with id:"cancel-comment)

<%= simple_form_for [@parent,@comment] do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.hidden_field :group_id, :value => @group_id %>
    <%= f.input :body, placeholder: 'Reply', label: false %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, 'Post Reply'%>
  </div>
  <%= link_to "Cancel", "#",id: "cancel-comment" %>

<% end %>

coffeescript: assets/comments.coffee:

$(document).on "page:change" , ->
  $('#cancel-comment').click ->
    alert "page has loaded!"
    return false

I also tried this:

$(document).on "page:change", ->
   $('#cancel-comment').click(e) ->
     e.preventDefault()
     alert "page has loaded!"

I also tried replacing the coffeescript with javascript as below but that didn't seem to help too:

$(document).on("page:change", function() {
    $('#cancel-comment').click(function(event) {
      event.preventDefault();
      alert("page has loaded!");
    });
  });

gemfile:

gem 'jquery-turbolinks'

assets/application.js

//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .
2
  • Is there a specific reason why you are using "page:change"? I would just change the entire first line (of your CoffeeScript file) to jQuery ->. That always works for me. Commented Feb 14, 2016 at 2:46
  • @mike Try page:load . Commented Feb 14, 2016 at 3:36

1 Answer 1

3
$(document).on "click", "a#cancel-comment", (e)->
  e.preventDefault()
  alert "page has loaded!"

Whenever we bind events to elements with Turbolinks, we delegate from the document and bind to the element directly.

--

If you're using Rails 5, you'll find that Turbolinks has changed its event hooks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.