meganlouise
meganlouise

Reputation: 35

Jquery works in console but not Rails 4 application.js file

This is my html markup: (in welcome/index.html.erb) in a Rails 4 project.

<div class="bottom-bottom-box box">
<div class="miv-box">
  <span class="five-yr thin-text">5-year</span></br>
  <span class="avg-return thin-text">Average Return</span>
</div>
  <span class="percent bold-text">19%+</span>
</div>

and this is my jquery: (in welcome.js) ( i don't know coffeescript so i just re-named the premade file to .js instead of .js.coffee )

$(".bottom-bottom-box").on('click', function() {
  alert('test');
  var el = $(this);
  if (el.text() == el.data("text-swap")) {
   el.text(el.data("text-original"));
  } else {
   el.data("text-original", el.text());
   el.text(el.data("text-swap"));
 }
});

My on click function to do the alert('test') won't even work, the weird part is when i type the exact same line in the console it works.

$(".bottom-bottom-box").on('click', function() { alert('test') });

Not sure what could possibly be wrong but if anyone has had this problem before pls let me know! thnx

Upvotes: 1

Views: 689

Answers (1)

Substantial
Substantial

Reputation: 6682

Sounds like .on() is being called before the .bottom-bottom-box elements are loaded into the DOM.

This is a common situation where Javascript included in the head runs before the body is loaded. Event handlers can only be attached to elements present in the DOM, which is why your code fails on page load (DOM empty), but works in the console (DOM loaded).

You can fix this by moving your JS includes to the bottom of the page, or tell jQuery to run your code after the DOM is loaded, like this:

$(document).ready(function() {
  $(".bottom-bottom-box").on('click', function() {
    alert('test');
    var el = $(this);
    if (el.text() == el.data("text-swap")) {
      el.text(el.data("text-original"));
    } else {
      el.data("text-original", el.text());
      el.text(el.data("text-swap"));
    }
  });
});

If you use Turbolinks, check out this answer: https://stackoverflow.com/a/18770589/1153362

Upvotes: 4

Related Questions