Reputation: 13
I want to place an Ad in a page column. When I scroll down, I want the Ad to follow all the way, but position in the vertical middle of the page. Using the script right now can only set a certain distance but cannot set exact 50% distance.
I have tired $window.height()/2
or $document.height()/2
, but they calculate my Table height instead of the actual screen height. How to solve this? Thanks!
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type="text/javascript">
$(function () {
var $sidebar = $("#sidebar"),
$window = $(window);
$window.scroll(function () {
if ($window.scrollTop() > $window.height() / 2) {
$sidebar.css('position', 'absolute');
$sidebar.css('top', $window.scrollTop() + $window.height() / 2);
$sidebar.slideDown(500);
} else {
$sidebar.css('position', 'auto');
$sidebar.css('top', 'auto');
}
});
});
</script>
</head>
<body>
<br><br>
<table bgcolor="#CCCCCC" width="800" height="3000" align="center" border="1">
<tr>
<td width="150" valign="top">
<div style="width:100px;height:100;background:white;"></div>
<br>
<div style="width:100px;height:100;background:blue;"></div>
<br>
<div style="width:100px;height:100;background:yellow;"></div>
<br>
<div style="width:100px;height:100;background:pink;"></div>
<br>
<div style="width:100px;height:100;background:maroon;"></div>
<br>
<!-- AD -->
<div style="width:100px;height:100;background:red;" id="sidebar">test</div>
<br>
</td>
<td width="500"></td>
<td width="150"></td>
</tr>
</table>
</body>
</html>
Upvotes: 1
Views: 444
Reputation: 6712
From jquery document, $(window).height();
should return height of browser viewport.
I represent the demo based on your html and js. It looks like your site now :)
see it: http://jsfiddle.net/FrFsP/1/
Upvotes: 1
Reputation: 6156
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
As documented here: http://api.jquery.com/height/
jQuery.fn.center = function(parent) {
if (parent) {
parent = this.parent();
} else {
parent = window;
}
this.css({
"position": "absolute",
"top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"),
"left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px")
});
return this;
}
$("div.target:nth-child(1)").center(true);
$("div.target:nth-child(2)").center(false);
Upvotes: 0
Reputation: 1340
If I got the idea right, I think this is what you are looking for just check out this example to see if this is it
If it's not what you are looking for, please can you clarify a little more?
Upvotes: 0
Reputation: 2296
You need window.innerHeight
to get the real dimensions (for modern browsers). Take a look at JavaScript - Get Browser Height for a small wrapper function.
Upvotes: 0