I’ve got a body background which must be relative to a page element (#container).
When the page is resized (smaller width) the container moves to the left (because it’s centered). The background should also be moving left with the same amount.
Now I’ve got the following code, which works for my problem:
/*
* The background must be relative to the rest of the page elements.
* The background position.left = 0px when the offset.left of the container = 362.
* The new background position.left is based on the current position of the container.
*/
var beginBackgroundPositionLeft = 362;
function changeBackgroundPosition() {
var newLeft = jQuery("div.container").offset().left;
newLeft = (-1 * beginBackgroundPositionLeft + newLeft) + "px";
jQuery("body").css("background-position", newLeft + " 0px");
}
jQuery(window).resize(function(e){
console.log(e);
// Change the position of the background
// when resizing the window.
changeBackgroundPosition();
});
jQuery(document).ready(function() {
// Change the position of the background on entering the page..
// Is needed because we don't know the resolution of the user so it can't be done with css.
changeBackgroundPosition();
});
It works fine, but it’s also executed when resizing the browser in height. How can I check if the browser is horizontal resized so resizing the height can be ignored?
Of course it’s possible to save the current window width and check if that’s changed but I’m looking for nicer way (and to learn something I don’t know yet;))!
As you can see, i’ve logged the ‘e’ of the resize function, but can’t find anything usefull to me in it..
Hope to learn something of your suggestions. Thanks!
This is how I would “do something” if only the window width was changed. There is not much in the resize event object that let’s you detect this in a nicer way I’m afraid. Perhaps you can find something in experimenting with percentages in the background-position CSS property: