Jeroen van der Wal Jeroen van der Wal -4 years ago 140
HTML Question

jquery console gives an undefined output on $('#div').height

I am using jquery for my header to be unfixed at a certain point. It works great but, when i try to get the height of my header it gives an undefined result.


<!DOCTYPE html>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src=""></script>
<script type="text/javascript" src="header.js"></script>
<div id="header">
<li><a href="#">Home</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>


$.fn.followTo = function (height) {
var $window = $(window);

$window.scroll(function (e) {
if ($window.scrollTop() > height) {
position: 'absolute',
top: height
} else {
position: 'fixed',
top: 0
var windowHeight = $(window).height();
var headerHeight = $('#header').height();
console.log(windowHeight, headerHeight);


As you can probably see the header.js is external, but that should not give any problems.

Answer Source

As you said thhat this code is in external file and you added it in <head>.So

What happen is:-

your jQuery code registered before the document is Ready/Rendered completely. That's why it will not recognize any HTML element and won't work

When you put it on bottom, it will wait for document to be Ready/Rendered properly and then your jQuery code will register and will recognize all HTML elements and start working

I hope it will clear your doubt now.


Load your external jquery file on the bottom of the current file.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download