Raven the Bard Raven the Bard - 1 month ago 4x
HTML Question

JavaScript loading out of time

I'm working in a Rails project and I was doing a simple click alert kind of function like this:


<%= button_tag 'button', type: 'button', class: 'right-button' %>


$(".right-button").on("click", alert("right-button clicked!"));

The problem is that when I load the page (ctrl + F5), the alert is triggered without even pressing the button and when I press the button, nothing happens. I already tried to use:

$(document).ready(function() {

But it didn't work either. I even tried to put the JavaScript insede the html.erb:

<%= button_tag 'button', type: 'button', class: 'right-button' %>
<script type="text/javascript">
$(".right-button").on("click", alert("right-button clicked!"));

If you know what is happening, please help, thanks!

PS: Turbolinks are disabled!


That's because you're immediately invoking your alert. Parenthesis after a function means that you're calling said function.

What you want to do is call alert from within your click handler's callback so that when the callback is invoked for your click event, the alert fires.

// Incorrect
$(".right-button").on("click", alert("Immediately Invoked"));

// Correct
$(".right-button").on("click", function() {
  alert("Invoked on-click");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="right-button">Click Me!</button>

Additionally if the element is injected dynamically, you'll have to turn to event delegation to handle that.

$('.add-section').on('click', function() {
  $('#container').append('<section><button class="click-me">Click Me!</button></section>');  

$('#container').on('click', '.click-me', function() {
  alert('Event delegation!!!!!!!!!!!');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
  <button class="add-section">Add section!</button>

What this does is targets a parent node of the dynamic content and attaches a click handler to it. We pass the selector that matches the node which will be dynamically added. Any clicks which occur on nodes within #container will be checked to see if they match .click-me, if they do then the callback will be fired.