William Hu William Hu - 1 year ago 94
CoffeeScript Question

CoffeeScript code only works after press home menu

I am using Rails 5. I have a

with index action and
root 'home#index'
. There's a button on index.html.erb, i want to press this button call some js code (pop window).

But my coffee script code only was call after i press Home menu. So i am wondering
are different? Thank you for your help.


<li><%= link_to "Home", "/"%></li>


<button id="myBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
<%= render :partial => 'stories/stories' %>


modal = document.getElementById('myModal');
btn = document.getElementById("myBtn");
span = document.getElementsByClassName("close")[0];
btn.onclick = ->
modal.style.display = "block"
span.onclick = ->
modal.style.display = "none"
window.onclick = (event) ->
modal.style.display = "none" if event.target == modal

Answer Source

Finally i got the reason: put the js code after the element defined which means DOM ready callback, here is JQuery DOM ready in CoffeeScript

$ ->
    console.log("DOM is ready")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download