0

Im having a hard time getting my Javascript to function without placing it within script tags. If I place it within the asset pipeline it will only work on the initial page load.

For example if im using UJ to append a menu to the page, it will be exempt from the pipeline JS.

ready = ->
  alert "page loaded"

  $('a').click ->
      alert "link clicked"


$(document).ready(ready)
$(document).on('page:load', ready)

This example above gives me the "page loaded" message at DOM ready, and the "link clicked" function will only fire for links which are on the page when it initially loads. If I use UJ to append another menu with links, clicking on the new links will not trigger the "link clicked" function. Its important to note that the links Im talking about have "remote: true" enabled.

If I place the raw JS form of the above script within script tags on the page it works fine for all links clicked.

Im wondering: how do use JS to control content which is appended after the initial DOM ready event?

greyoxide
  • 1,197
  • 1
  • 17
  • 45
  • When a listener is attached to a certain selector, the browser will attach it to elements which exist in the DOM at that moment, and will not create a global hook. Because of this, all new elements inserted into the DOM after the initial page load will need to have listeners attached to them at the time of insertion. – Alexa Y Aug 28 '15 at 18:59
  • so... would I call page specific functions from within the html page? – greyoxide Aug 28 '15 at 19:03
  • If you're using js.erb (which is sounds like you are), you could assign the new element to a variable, append the variable to the desired parent container, and then attach a listener to it all within the template. – Alexa Y Aug 28 '15 at 19:06
  • having at best a rudimentary understanding of JS: Im not certian how to go about this. Could you point me to an example I could follow? – greyoxide Aug 28 '15 at 19:28
  • As an example of what @Ben Y is talking about, see the accepted answer on this question - http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements In short, you want to do something like this (attach to body or the closest parent element) `$('body').on('click', 'a.myclass', function() { // do something });` – furman87 Aug 28 '15 at 19:37

0 Answers0