0

When i use jquerys .offset() or .position() function they always return undefined. When i type them in the console i get they same result but eval(?) returns the correct value. Why is that? Im new to jquery so im a bit confused.

error img

html:

<!DOCTYPE html>

<head>
    <title>r</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="style.css">
    <script src="index.js"></script>
</head>

<body>

<div class="container">
    <div class="inner">

    </div>
  </div>
</body>

css:

body {
    height: 100%;
    width: 100%;
}

.container {
    width: 100%;
    position: relative;
    float: left;
    background: #fff;
    height: 1200px;
  }

  .inner {
    width: 150px;
    height: 100px;
    position: absolute;
    top: 20%;
    left: 10%;
    background: red;
  }

js:

var offset = $(".inner").offset();
$(window).scroll(function(event) {
  var st = $(this).scrollTop();
  $(".inner").css("left", st + offset.left);
});
  • 2
    Put the code inside `$(document).ready()` – Barmar Mar 23 '20 at 22:25
  • To expand upon @Barmar's comment: you are loading your script in ``, before the DOM has been parsed and loaded. At the time the script is executed, the element you are looking for does not yet exist. Waiting for the `DOMContentLoaded` event in vanilla JS, or using the above wrapper, will prevent this issue. – chriskirknielsen Mar 23 '20 at 22:28

0 Answers0