Javascript error ‘cannot read property of undefined’

csshtmljavascriptjquery

The javascript, html and css work in this jsfiddle
but when entered into an html file like so:

<!doctype html>
<html>
  <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="chrome=1">
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
        <script type="text/javascript">
            var target = $(".mypara").offset().top;
            var interval = setInterval(function() {
                if ($(window).scrollTop() >= target) {
                    alert("made it!");
                    clearInterval(interval);
                    }
            }, 250);
        </script>
        <style>
            body {
            background-color: linen;
            height: 1000px;
            }
            p {
             color: blue;
              margin-top: 500px;
            }
        </style>

    </head>
    <body>
     <p class="mypara">asdfasdfasf</p>
    </body>
</html>

chrome console gives this error

Uncaught TypeError: Cannot read property 'top' of undefined(anonymous function) @ index – Copy.html:8

This error refers to line 8:

var target = $(".mypara").offset().top;

Can someone help me understand why?

Best Answer

Wrap your code in

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

You're trying to access an element in the DOM before it exists so when your trying to access the class the item doesnt exist yet. Or move your script below the elements in the html

Works in fiddle cause thet wrap you're code depending on your setting which defaults to domready I believe