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.

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="header.js"></script>
</head>
<body>
<header>
<div id="header">
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">Contact</a></li>
<li><a href="#">About</a></li>
</ul>
</nav>
</div>
</header>


Jquery

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

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

$('#header').followTo(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.

Solution:-

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