Ignacio Palma Balboa Ignacio Palma Balboa - 6 months ago 11
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:

$("header").hide();


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

function myCode() {
$("header").hide();
}

$(document).ready(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

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.

Comments