Skip to content

Instantly share code, notes, and snippets.

@DfKimera
Created July 12, 2011 19:17
Show Gist options
  • Save DfKimera/1078738 to your computer and use it in GitHub Desktop.
Save DfKimera/1078738 to your computer and use it in GitHub Desktop.
maxLeft calculation using browser viewport in jQuery (for absolute positioning)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body style="overflow: hidden; margin: 0;">
<div id="portfolio" style="width: 2000px; position: relative; border: 3px solid red; background: #eee; left: 0;">asdf asdf asdf asf asdf asdf asdf sfdg fghfgh jhgj hjkjlh fb vc bxcvb xcb etr 43g545i45hghw3 083wh 0f89wh3 9f8wh349f8w3hf9 8hf9 8w3h4f9 8w3h4f9 8w3h4f 9w83hf 9w34f 09w384hf 9w348f hw34hf ow3ih f9w384 fh9w348fy w93 fw34n fiuhiefundriugshr98</div>
<div>
<input type="text" value="0" id="disp-left" />
<input type="text" value="0" id="disp-max" />
<a href="#" onClick="goLeft(); return false"> &lt;&lt;</a>
<a href="#" onClick="goRight(); return false"> &gt;&gt;</a>
</div>
<script type="text/javascript">
var currentLeft = 0;
var maxLeft = 0;
$(window).resize(recalculateMaxLeft);
function recalculateMaxLeft() {
maxLeft = 0 - ($('#portfolio').width() - $(window).width());
$('#disp-max').val(maxLeft);
}
function goLeft() {
currentLeft += 50;
if(currentLeft > 0) {
currentLeft = 0;
}
$('#portfolio').css('left',currentLeft+"px");
$('#disp-left').val(currentLeft);
}
function goRight() {
currentLeft -= 50;
if(currentLeft < maxLeft) {
currentLeft = maxLeft;
}
$('#portfolio').css('left',currentLeft+"px");
$('#disp-left').val(currentLeft);
}
$(function () {
recalculateMaxLeft();
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment