Josef Tinagan Josef Tinagan -4 years ago 190
CoffeeScript Question

Rails Coffeescript code not working, but works if I use a simple <script> tag in the bottom of my page

I'm making a simple modal for a website, the problem is, the coffescript is not working while if I put a tag on the bottom it works. Am I wrong to think its because the coffescript is loading first than the page? Or is it something else entirely?

I use this http://js2.coffee/, to convert javascript to coffeescript.

RelevantCode

Relevant HTML:

<div class="row home-page-pictures-container">
<div class="col-md-10 col-md-offset-1">
<%= image_tag("test.jpeg", id: "img1", class:"img-thumbnail") %>
<%= image_tag("glasses-stock.jpeg", id: "img2", class:"img-thumbnail") %>
<%= image_tag("glasses-stock.jpeg", id: "img3", class:"img-thumbnail") %>
<%= image_tag("glasses-stock.jpeg", id: "img4", class:"img-thumbnail") %>
<%= image_tag("glasses-stock.jpeg", id: "img5", class:"img-thumbnail") %>
</div>

<div id="modal" class="modal-container">
<span class="close">&times;</span>
<img id="img-modal" class="modal-content">
<div id="caption"></div>
</div>
</div>




There should be no problem with the CSS since when I uncheck the display: none in the div of modal. it's there.

What am I missing here?

Answer Source

If the code works properly in a script tag at the bottom of a document, but not in a file loaded at the top, then you're right to think its code load order.

I think the problem here is that you're loading the file at the beginning of your DOM and binding element behaviour before these elements get rendered into the document. Hard to tell without the your code though.

JQuery has a method to bypass this problem.

$(document).ready(function() {
  # waits till the document is ready to do stuff
  $('#my_elem').click(function() { 
    console.log('do stuff') 
  }
})

This waits and listens for the DOMContentLoaded event in JS, before running any of your code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download