Issues with Javascript positioning in Chrome and Safari are causing some functionality to malfunction

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.

Answer №1

Let's address the issues at hand:

1) The code contains references to "slide1Width" and "slide1" which are not defined anywhere. 2) There is a discrepancy in the number of closing brackets, with an extra semicolon after the last bracket. 3) An error lies in the expression (slideWidth.replace("px", "") + 1), resulting in unexpected behavior.

Upon further investigation, it appears that timing might be the root cause of the actual bug you're experiencing. By running slideImageWidth() manually after the page has fully loaded, the image centers correctly even on Chrome. The issue seems to stem from the initial width calculation of the element before it finishes loading completely.

Answer №2

Instead of using setTimeout, have you considered utilizing a resize event? Here's an alternative approach:

window.onresize = function(event) {
    adjustSlidePosition();    
};

function adjustSlidePosition() {
    var slideLeft = (document.getElementById("slide-image").style.left.indexOf('px') != -1 ) ? document.getElementById("slide-image").style.left : '0px';

    var numLeft = slideLeft.replace('px','');

    console.log(numLeft);

    var element = document.getElementById("slide-image")

    if(element.width > window.innerWidth) {
        var newLeft = (element.width - window.innerWidth) / 2 * -1 + "px";
        document.getElementById("slide-image").style.left = newLeft;
    } else {
        document.getElementById("slide-image").style.left = "0px";
    }
};

adjustSlidePosition();

http://jsfiddle.net/4qomq7tb/45/

This appears to work consistently in both Chrome and Firefox. While it may not directly address the specific question regarding your code, it offers an alternative solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal method for a React and HTML Select-component to output String values instead of Integer values

Within my React-class (JSX), I've included the following code: var Select = React.createClass({ onChange: function (ev) { console.log(ev.target.value); }, render: function() { var optionsHtml = this.state.options.map(function (el) { ...

Incorporating a complex React (Typescript) component into an HTML page: A Step-by

I used to have an old website that was originally built with Vanilia Javascript. Now, I am in the process of converting it to React and encountering some issues. I am trying to render a compound React(Typescript) component on an HTML page, but unfortunatel ...

Display or conceal various content within div elements using multiple buttons

I have a set of 5 image buttons, each meant to trigger different content within a div. When the page loads, there should be default content displayed in the div that gets replaced by the content of the button clicked. The previously displayed content shoul ...

Creating a user-friendly interface for the admin to easily upload photos by implementing a php/bootstrap/js code within the panel

I'm currently in the process of creating an online website as part of my thesis project. I've been researching this specific code, but unfortunately, I haven't been able to find a solution. In the admin section of the site, I need to enable ...

When hosted, OpenCart encounters a JavaScript error stating that the property "document" cannot be read because it is null

After successfully running opencart on my local machine, I encountered some errors upon uploading it to the hosting/server. The specific error message is as follows: Uncaught TypeError: Cannot read property 'document' of null f.each.contents @ j ...

Is there a way to set up a listener for a particular property of a recoil state object?

Is it possible to create a listener for a specific property within a state object? Let's look at an example: type ExampleAtomProperties = { id: number; description: string; }; const ExampleAtom = atom< ExampleAtomProperties>({ key: &quo ...

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

Issue encountered while attempting to load bootstrap in NodeJS

I encountered an error while running my jasmine test case in node. The error message says that TypeError: $(...).modal is not a function. This error pertains to a modal dialog, which is essentially a bootstrap component. To address this issue, I attempted ...

Showing formatted JSON (Large Object) on an HTML page

Having trouble displaying formatted JSON in an HTML page, especially when dealing with larger objects (an array of objects). The current method involves using JSON.stringify(data) to display the JSON object upon receiving a response from the server. The P ...

The jQuery .post method is not returning any data when using the done and fail functions

I've encountered an issue while attempting to execute a jQuery AJAX request and retrieve the data in the .done and .fail methods. Below is the snippet of code that triggers the AJAX request: async function doSomething(){ const addressValid = awai ...

Retrieve data from a JSON file

I have a JSON file containing various player data, and I need to extract the "Name" field from it. { "player": [ { "Position": "TEST", "Name": "TEST", "Squad_No": "TEST", "Club": "TEST", "Age": "TEST" }, ...

The accuracy of the fromPointToLatLng function in Google Map's JS API seems to be inconsistent with the actual events

My objective is to enhance user experience with a drawing tool on the map interface. I aim for a functionality where, upon single-clicking somewhere on the map using tools like the rectangle tool, the map automatically centers on that clicked location. Thi ...

Creating an AJAX function to display a popup window for users who are already registered - here's how!

I am currently working on a dropwizard-java project. Whenever users click the subscribe button, it displays a thank you message for subscribing and then checks if the user is already registered. I would like to have a pop-up window immediately show whethe ...

Combine functions from two objects that share the same properties into an array for each property

I need help combining the methods from two objects into one, resulting in an array of methods for each property in the parent object: obj1 = {"prop1":"method1","prop2":"method2"} obj2 = {"prop1":"method3","prop2":"method4"} Expected result: obj1 = {"pro ...

Error in Node Express server: Status code 0 is not valid

As a beginner node.js/js programmer, I am encountering an error code while trying to make a POST request on my application. The error message reads as follows: Error: [20:22:28] [nodemon] starting `node app.js` Running server on 3000 Mon, 27 Jun 2016 19:2 ...

What is the best way to deliver HTML content to an ASP.NET MVC JSON function?

Here is my jQuery code that I have written along with the json function called InsertMatlabJson. However, I am facing an issue where no text is being passed to the .NET json function. function insert() { var url = '<%=Url.Content( ...

Angular identifies when a user navigates away from a page

Currently, I am utilizing Angular 1.5 along with ui-router. My goal is to identify when a user exits a route. The code snippet I have at the moment looks like this: $scope.$on("$stateChangeSuccess", function () { if (!$scope.flag) { //... ...

I'm looking for help on creating a three-column table using javascript/jquery. The table should display Product, Price, and Discount (which is calculated at 20%). Can anyone

Check out this code snippet. var items = ["Laptop", "Tablet", "Smartphone", "Headphones", "Camera"]; var costs = [599.99, 299.99, 799.99, 149.99, 499.99]; displayItems = ""; totalCost = 0; for (var j = 0; j < items.length; j++) { displayItems += " ...

Navigate to the correct page when the Button is clicked in a ReactJS/Django project

Embarking on my web development journey, I opted for django/Reactjs to build a social network platform. I created several API methods like account/view_user/ to retrieve a list of users and account/view_user/ for specific user attributes. In React, I cra ...

When render returns another component, React does not invoke componentWillMount

Here is my code setup: const Dashboard = React.createClass({ getInitialState(){ return { user: JSON.parse(localStorage.getItem('user')) }; }, componentWillMount(){ var self = this; $.get({ url: 'http://127 ...