My Javascript script is designed to keep an image centered in the window even when the window is smaller than the image. It achieves this by adjusting the left offset of the image so that its center aligns with the center of the screen. If the window is larger than the image, the left offset is set to zero. This functionality works flawlessly on IE and Firefox. However, on webkit browsers, the left offset never goes to zero, resulting in a strange behavior resembling float:right
when the window is wider than the image. Here's the code snippet:
setTimeout(slideImageWidth, 1);
function slideImageWidth() {
var slideWidth = window.getComputedStyle(document.getElementById("slide-image")).width,
windowWidth = window.innerWidth,
slide = document.getElementById("slide-image"),
slideWidth = window.getComputedStyle(slide).width;
if (windowWidth < (slideWidth.replace("px", "") + 1) && slide.style.display !== "none") {
slide.style.left = ((((-slideWidth.replace("px", "") + windowWidth)) / 2) + "px");
}
else {
slide.style.left = 0;
setTimeout(slideImageWidth, 1);
};
I've tried different ways to set slide.style.left
to zero before the condition, but none have worked in Chrome or Safari. The interesting part is that all methods except the last one worked in IE and Firefox.
When I use alert(slide.style.left)
on Chrome and Safari, it returns a positive value when the window is wider than the image. This suggests that the zero value is not being assigned to slide.style.left
. Despite this, the image still positions itself correctly based on the equation.
The puzzle remains why this code behaves differently on webkit browsers and how I can resolve it.