Riley Shaw
Riley Shaw

Reputation: 321

JavaScript not finding elements in layout

I have a ruby on rails program that displays the flash message in the application layout as such:

<% if flash[:notice] %>
   <p id="notice">
      <span id="notice-button-left">[-]</span>
      <%= flash[:notice] %>
      <span id="notice-button-right">[-]</span>
   </p>
<% end %>

and on clicking the <spans> #notice-button-left and #notice-button-right, I want the <p> to disappear so I added the code:

document.getElementById("notice-button-right").addEventListener("click", function(){
    document.getElementById("notice").style.display = "none";
});

document.getElementById("notice-button-left").addEventListener("click", function(){
    document.getElementById("notice").style.display = "none";
});

to a <script> tag and threw it in the application.html.erb layout. This worked perfectly. However, when I took out the <script> tag and threw the js into a .js file in the app/assets/javascripts folder it stopped working. When inspecting the browser it appears to be finding the js file, but the js just isn't working.

Note One: I have another script that is working

Note Two: I have turbolinks turned off

What I would like is to have the script work and have the notice disappear on clicking the spans.

Upvotes: 1

Views: 50

Answers (2)

blixxurd
blixxurd

Reputation: 11

Load your script right before the </body> if it's currently in the <head>. It's quite likely that the DOM Content that your script references is not present yet. Loading scripts after the markup renders should fix this, and provide better speed to your website.

The alternative is to wrap your scripts in the DOMContentLoaded event, but typically you are going to want to keep your scripts further down the page in either case.

Upvotes: 0

jsanderlin
jsanderlin

Reputation: 154

Try wrapping your javascript code in a document ready, since it appears you're not using jQuery, something like this should work in the app/assets/javascripts folder:

document.addEventListener("DOMContentLoaded", function(event) { 
  document.getElementById("notice-button-right").addEventListener("click", 
    function(){
      document.getElementById("notice").style.display = "none";
    });

  document.getElementById("notice-button-left").addEventListener("click", 
    function(){
      document.getElementById("notice").style.display = "none";
    });
});

Upvotes: 3

Related Questions