Ignacio Palma Balboa Ignacio Palma Balboa - 1 year ago 63
jQuery Question

jQuery not working straight away

I am working on Ruby on Rails and a simple jQuery won´t execute over an element like this:


However, if i wrap it into a function and call it with document.ready it does the right thing:

function myCode() {


Why it does not work straight forward?? I have installed gem jquery-rails and even have //=required jquery.min.js in the application.js file.

Thanks for the help!

Answer Source

If the document is not ready, the DOM isn't built yet. The header element doesn't exist when that code runs, so nothing happens. To perform DOM manipulation, you must wait until the page is fully loaded, that is, on $(document).ready.