简体   繁体   中英

moving javascript into assets folder

im trying to move my javascipt from the view page, where it works, into the assets/javascripts file. However when i make the move, the javascript no longer executes. Im not sure why?

 $('.dropbtn').click(function(){ if($(this).hasClass("active") ) { $(this).parent(".dropdown").find('.dropdown-content').removeClass('show'); $(this).removeClass('active'); } else{ $('.dropdown-content').removeClass('show'); $(this).parent(".dropdown").find('.dropdown-content').addClass('show'); $(this).addClass('active'); } }); 

If your Javascript file is included in the asset pipeline it will be concatenated, minified and preprocessed into one big .js file that is included -by default- in your layout's <head> . By the time the browser is reading this file, the dom element associated with the .dropbtn class hasn't loaded yet, so the click event listener never gets added.

The solution would be to wrap your code inside a function that gets called once the document has loaded:

$(document).ready(function(){
  // your code goes here.
});

However, if you're using turbolinks (which is included by default in rails) you need to use:

$(document).on('turbolinks:load', function(){
  // your code goes here.
});

The reason for this is that once the document is loaded, turbolinks will update it instead of reloading it after each request, so $(document).ready() will only fire once while 'turbolinks:load' will fire every time there's content loaded by turbolinks in your app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM