Graham Slick
Graham Slick

Reputation: 6870

Javascript on page load: works in console, but not on load

I want to run this javascript on my homepage when it loads:

  $(".mm-page").css({"position":"inherit"});

I added this at the bottom of my home.html.erb:

<% content_for(:after_js) do %>
  <script type="text/javascript">
    console.log("before");
    $(".mm-page").css({"position":"inherit"});
    console.log("after");
  </script>
<% end %>

Both console.log appear in the console, but the jquery has no effect. If I manually run the jquery line in the console, it works as expected.

How should I proceed to fix this ?

Upvotes: 1

Views: 2109

Answers (3)

Rino Raj
Rino Raj

Reputation: 6264

Since you want to make it work on page when it load you should wrap it inside ready handler.The ready() method specifies what happens when a ready event occurs.

Two syntaxes can be used:

$(document).ready(function(){
     $(".mm-page").css({"position":"inherit"});
});

OR

$(function() {
    $(".mm-page").css({"position":"inherit"});
});

Also be sure that the element .mm-page exists in the moment you're using it with the jQuery selector.

Upvotes: 2

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

console.log appear in the console 

Because your DOM has finished loading and it is now ready to use.

That's why you are getting jQuery effect.

In your current script,it is not waiting to finish DOM loading and directly operating on it which is not available as it is not finished loading.

Eiher write script it in

$( document ).ready(function() {
  // Handler for .ready() called.
});

OR :

$(function() {
  // Handler for .ready() called.
});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074238

To ensure that all of the DOM elements it operates on exist, put the script tag at the very bottom of the HTML, just prior to the closing </body> tag. All of the elements defined by the HTML above it will then be available for use. This also ensures that the browser can show the user the page prior to downloading any external script files you reference. E.g.:

<!doctype html>
<html>
<!-- ...your page here... -->
<script src="jquery.js"></script>
<script>
  console.log("before");
  $(".mm-page").css({"position":"inherit"});
  console.log("after");
</script>
</body>
</html>

You'll need to translate that to whatever rendering engine you're using, but you get the idea. The end result going to the browser should look like that.

Alternately, you can use jQuery's ready callback, but with the script tags in the correct location, it's unnecessary.


Side note: The default type is JavaScript, there's no need to specify it on the script tag.

Upvotes: 1

Related Questions