William Hu William Hu - 3 months ago 9
CoffeeScript Question

CoffeeScript code only works after press home menu

I am using Rails 5. I have a

home_controller
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
/
and
home#index
are different? Thank you for your help.

application.html.erb

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


index.html.erb

<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>
</div>
</div>
<%= render :partial => 'stories/stories' %>


home.coffee

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

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")