megahra
megahra

Reputation: 335

Coffeescript on click event not firing?

I am working on a Ruby on Rails project where clicking a link_to element on my view is supposed to trigger a method in my CoffeeScript, but the output is never printed!

This is the relevant part of my HTML (the link works):

<%= link_to 'Start Quiz!', {:controller => :pages, :action => :start_quiz}, :id => 'btn btn-primary btn-lg', :method => :get %>

This is the method in my ActionCable CoffeeScript file:

App.quiz_data = App.cable.subscriptions.create "QuizDataChannel",
  connected: ->
    console.log "[AC] on click handler called?"
    $(document).on('turbolinks:load', -> $('btn btn-primary btn-lg').on 'click', -> console.log "[AC] on click handler called!")

My console reads "[AC] on click handler called?" but nothing else, even after I click on the link.

I've been googling a lot and a few posts suggested the problem might be with turbolinks. The above code already reflects 2 of several solutions I've tried (specifying get method in link, enclosing event handler with $(document).on('turbolinks:load', -> ...)), none of which fixed it for me. I'm a Rails beginner and have no clue about CoffeeScript, so any help would be greatly appreciated.

EDIT:

After adding the id selector # and deleting the get method in the link_to element and $(document).on('turbolinks:load', -> ...) in the event handler - it finally works! :D

HTML element now:

<%= link_to 'Start Quiz!', {:controller => :pages, :action => :start_quiz}, :class => 'btn btn-primary btn-lg', :id => 'start_quiz_button' %>

CoffeeScript file now:

App.quiz_data = App.cable.subscriptions.create "QuizDataChannel",
  connected: ->
    console.log "[AC] on click handler called?"
    $('#start_quiz_button').on 'click', -> console.log "[AC] on click handler called!"

Thank you! :)

Upvotes: 0

Views: 915

Answers (1)

Othmane El Kesri
Othmane El Kesri

Reputation: 603

1) You need to change your id to a valid one (read this post), something like start_quizz_button

2) Use an id-selector # :

$(document).on('turbolinks:load', -> $('#start_quizz_button').on 'click', -> console.log "[AC] on click handler called!")

Upvotes: 1

Related Questions