When my page loads, I want to automatically jump to a specific anchor tag and ensure that the anchor object is centered in the window. Initially, I implemented a basic function to achieve this:
<body onload="goToAnchor();">
<script type="text/javascript">
function goToAnchor() {
window.location = "#center";
}
</script>
However, in order to center the anchor object, I needed to adjust the window's location. To accomplish this, I used the following code snippet in another function, which calculated the necessary offset (assuming a fixed width of 1500px for the object):
var $offset_target = (1500 - $(window).width())/2;
This approach successfully ensured that the anchor object was always centered within the viewport whenever it was jumped to.
Do you have any alternative suggestions or ideas?
Thank you!
UPDATE/ANSWER
After considering two helpful replies below, I devised a solution using the following code:
function goToAnchor() {
document.body.scrollLeft = document.documentElement.scrollLeft =
document.getElementById('center').offsetLeft-
(Math.ceil((- 1500 + $(window).width()) / 2));
}
While not the most elegant solution, it effectively accomplishes the desired outcome! Thank you for your input. If you have a more efficient method to achieve this, please share!