UserDuser
UserDuser

Reputation: 461

Rails button click not firing custom JS function

The following code works in jsfiddle to hide a div but not in my Rails app. In my rails app, a remote javascript call is made to show the div that I intend to hide when a Cancel button is clicked:

<form id="new_thing" class="new_thing" method="post" data-remote="true">
  <input></input>
  <input></input>

  <input class="btn btn-primary" type="submit" value="Submit" name="commit" id="fuck">
  <button id="thing_cancel" class="btn btn-primary" type="button" name="button">Cancel</button>

 </form>

The JS:

  $("#thing_cancel").click(function () {
    $('#new_thing').hide();
  });

In my app, I try:

<%= button_tag "Cancel", :class => "btn btn-primary", :type => "button", :id => "position_cancel" %>

where clicking the button does nothing. Adding :remote => true and using link_to has yielded the same result.

With, in my assets/javascripts/thing.js:

$('#thing_cancel').click(function(){
  event.preventDefault();
  $('#new_thing').hide();
  $('#new_thing_link').show();
});

I've found several somewhat related questions but nothing has worked thus far. Is there something I'm missing with the whole turbolinks thing? I have:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .    
//= require jquery.turbolinks

Upvotes: 1

Views: 3742

Answers (1)

Mandeep
Mandeep

Reputation: 9173

It's happening because rails 4 ships with turbolinks gem. If you look at rails guides. It says

Turbolinks will make an Ajax request for the page, parse the response, and replace the entire <body> of the page with the <body> of the response.

You need to put your js code inside application.js or a new file which is required inside application.js. To workaround turbolinks you have following options:

a. You can wrap your jquery code inside a function and then call that function on page load. If your function is myfunction then you can do:

$(document).ready(myfunction);
$(document).on('page:load', myfunction);

b. You can use jquery's live event or "on" event:

$(document).on("click","#thing_cancel",function(){
  $('#new_thing').hide();
  $('#new_thing_link').show();
});

c. You can use the jquery-turbolinks gem which will bind the Rails Turbolink events to the document.ready events so you can write your jQuery in the usual way. For more information refer to here

Upvotes: 3

Related Questions