Safari: Fixed-positioned DIVs staying put after DOM updates

Hey there!

I've been experimenting with animating absolutely positioned DIVs on my webpage using some JavaScript to update the top and left CSS properties. It's been working smoothly in Chrome, Firefox, and even Internet Explorer 8. However, I encountered a strange issue when testing it in Safari 5 - the DIVs just remain static. Oddly enough, if I resize the Safari window, they suddenly start moving...

If you're curious, you can check out a demo of what I'm talking about here:

The code used to update the DIVs is quite simple, just a snippet of jQuery (which also handles rotation perfectly fine in Safari):

$(this.elem).css({
 '-webkit-transform': 'rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)',
 '-moz-transform': 'rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)',
 'transform': 'rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)',
 'left': Math.round(this.xPos) + 'px',
 'top': Math.round(this.yPos) + 'px'
});

I tried adding position:relative to the body, as well as including 'px' and rounding down the values in case Safari was finicky about long floating point numbers. Sadly, no luck - the DIVs stubbornly refuse to budge until the window gets resized...

If you have any insights or suggestions, they would be greatly appreciated!

Thanks for reading, Chris.

Answer №1

To fix the issue in Safari 5, replace the top and left properties with the translate sub-property of the transform CSS property.

When using setInterval, avoid using string arguments.

Demo: http://jsbin.com/okovov/2/

Bird.prototype.draw = function() {
    var transform = 'rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)' +
                    ' translate('+ this.xPos + 'px,' + this.yPos + 'px)';
    $(this.elem).css({
          '-webkit-transform': transform,
          '-moz-transform': transform,
          'transform': transform
    });
};
// ...
var timer1 = setInterval(function(){bird1.animate();}, 50);
var timer2 = setInterval(function(){bird2.animate();}, 50);
var timer3 = setInterval(function(){bird3.animate();}, 50);

A smaller delay than 50 milliseconds could improve animation performance. Consider optimizing your functions by replacing jQuery methods with vanilla JavaScript:

Bird.prototype.draw = function() {
    this.elem.style.cssText = ['-webkit-', '-moz-', '', ''].join(
        'transform:rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)' +
        ' translate(' + this.xPos + 'px,' + this.yPos + 'px);'
    ); // Result: -webkit-transform: ...;-moz-transform:...;transform:...;
};

Answer №2

This solution may not fit your exact needs, but you might consider utilizing jQuery's .offset() to adjust their position instead of manually modifying their CSS properties. Your implementation would resemble the following:

$(this.elem).css({
 '-webkit-transform': 'rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)',
 '-moz-transform': 'rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)',
 'transform': 'rotate(' + (( this.angle * (180 / Math.PI) ) * -1) +'deg)'
})
.offset({
 top: Math.round(this.yPos),
 left: Math.round(this.xPos)
});

I trust this guidance proves helpful!

Sidenote: if you wish to establish the relative position, leverage jQuery's .position().

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

Using Typescript, Angular, and Rxjs to retrieve multiple HttpClients

I am looking to send get requests to multiple endpoints simultaneously, but I want to collect all the responses at once. Currently, this is how a single endpoint request is handled: public getTasks(): Observable<any> { this.logger.info('Ta ...

How to create a dropdown menu in React js with an array of items

Can we structure the array without splitting it into two parts and iterating over them? arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products] <div className='Flexbox'> //arrayList1.map](//arrayList1.map)(x=>return(< ...

Utilizing PHP to dynamically load HTML forms and leveraging JQuery for form submissions

I am currently facing a dilemma that I am unsure how to approach. It seems that JQuery requires unique ID's in order to be called in the document ready function. I use PHP to read my MySQL table and print out HTML forms, each with a button that adds a ...

In Redux, it is possible to add characters to an array but for some reason the remove action does not successfully reach the reducer

As a user types or erases characters, I am utilizing redux to update an array of characters. This allows me to set a success flag when the user correctly types the entire phrase. Currently, when typing in characters, the SET_INPUT action in redux fires of ...

How to Deactivate Horizontal Scrolling Using CSS in WordPress

Hey there, I'm currently working on a WordPress blog and facing an issue. Here's the link to my problem: When I resize the browser (X-Axis) to a minimum, like when using a mobile device, I noticed that I can scroll to the right in the Content se ...

Injecting HTML into Vue component

Currently, I am passing some parameters into a Vue component <Slider :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']" :html="['<div>hello</div>', ' ...

Is it impossible to access the length property of an undefined variable?

After developing a function that calculates the length of a string entered into an HTML textbox, I encountered an error when trying to display the result in another textbox. The function is designed to get the value from the 5th textbox on my HTML page and ...

"JavaScript's versatility shines through with its ability to handle multiple variables

Presently, I am working with the following script: <v-tab :title="siteObject.xip_infos[index].lineid" > <div class="description text-left" :class="{ 'text-danger': item.status === 'DEACTIVE' }"> <small v-for="(f ...

The functionality of Material UI tooltip is not functioning properly when accessed on mobile devices

Attempting to transform Tooltip into a controlled component that relies on the onClick event. While this setup works well on mobile and web, it loses its original functionality of showing the Tooltip on hover. Is there a way to make the Tooltip function ...

Stopping repeated content with endless scrolling ajax spinner

It seems like my mind is too foggy from the late night hours to find a clear solution, so I thought I'd seek some input from those who have an opinion... The website project I'm currently working on features a lengthy list of user posts. I' ...

Steps to customize Button Color and Label in a specific cell within a Material UI Table

I've implemented the Material Table to display my data, and it seems like this: In my code, I have a declared state as follows: const [sharedOrdersList, setShareOrdersList] = useState([]) When the User clicks the Share button, I push the Order Id in ...

What is the best way to have child controllers load sequentially within ng-repeat?

Currently, I have a main controller that retrieves data containing x and y coordinates of a table (rows and columns). Each cell has a child controller responsible for preparing the values it will display based on the x and y values from the parent control ...

Can JavaScript trigger an alert based on a CSS value?

Hello, I am facing an issue. I have created a blue box using HTML/CSS and now I want to use JavaScript to display an alert with the name of the color when the box is clicked. Below is my code: var clr = document.getElementById("box").style.background ...

Launching a jquery dialog from a sibling anchor element without relying on selectors based on IDs

Struggling to solve a simple issue using jQuery UI's dialog function. The challenge lies in displaying custom explanations for search results within dialog boxes triggered by help links. Each result may have notations with corresponding help links tha ...

The jQuery AJAX autocomplete result box is either too cramped or displaying numbers

I'm having some trouble setting up jQuery UI autocomplete with ajax in my project using CI 3.1.5. When I try to implement it, I either get a small result box or just the number of results. Here is my AJAX code snippet: $(".addClient").each(funct ...

What is the best way to target all the 'tr' elements within a 'table' using angularJS?

I have developed a customized directive that is targeted at a 'tr' element within a table. <tr row-select > I am looking to eliminate a specific style from all 'tr' elements under that particular table. directiveApp.directiv ...

Error encountered in Vue3: An uncaught TypeError occurred when attempting to "set" a property called 'NewTodo' on a proxy object, as the trap function returned a falsish

I encountered an error message: Uncaught TypeError: 'set' on proxy: trap returned falsish for property 'NewTodo' This error occurs when attempting to reset the input text value within a child component (FormAddTodo.vue). App.vue: expo ...

When an element is set to a fixed position while scrolling, it causes the element to flicker

After implementing the jQuery plugin stickyjs on my website, I noticed a strange issue. While it works perfectly fine on my Mac, when using the mouse scroll wheel on my PC, the element blinks once rapidly as it reaches the top of the page. Interestingly, d ...

Explain how the 'next' function works within Express middleware and its role in directing the flow to a different function

I am fairly new to Node.js and currently learning Express.js. I am focusing on implementing "middleware functions" for specific routes. My question is regarding the usage of the "next" function. What exactly can we do after authentication using the "next ...

Why do I keep receiving the error message "Cannot set property of undefined"?

In the midst of a small project that involves utilizing nuxt, js, and axios, I encountered an issue when attempting to assign the response data to my formFields object. Despite having declared formFields within the data section, I kept receiving an error m ...