Dynamically select css property in animation

It seems to be simple, but I don't have much success. I just embed a simple animation by moving the div to the left or up using animate (), but I would like to dynamically set the "top" and "left" css properties. I would like to use the same function, and not have two, one for the "left" and one for the "top".

Here is some code that gives an idea.

function test($element){ $element.click(function(){ var cssProperty; var direction = "left"; var moveTo = "100px"; if (direction === "top") { cssProperty = "top"; } else { cssProperty = "left"; } /*Using variable as CSS property - This doesn't work */ $(this).animate({ cssProperty: moveTo }, 1000); /*Using variable as the CSS Values - This does */ $(this).animate({ left: moveTo }, 1000); }); } 

Variables work with the css value side, but not with the css selector. Anyone have any suggestions?

thanks

+4
source share
3 answers

See this: http://www.jibbering.com/faq/faq_notes/square_brackets.html

 function test($element){ $element.click(function(){ var cssProperty; var direction = "left"; var moveTo = "100px"; var animationProperties = {}; if (direction === "top") { cssProperty = "top"; } else { cssProperty = "left"; } animationProperties[cssProperty] = moveTo; // This does work. $(this).animate(animationProperties, 1000); // Or else, using computed properties introduced in ES6. $(this).animate({ [cssProperty]: moveTo }, 1000); }); } 

Browser support for computed properties .

+3
source

The "idle" part does not work because you simply cannot use variable values ​​to declare fields in JSON. To get around this, you should have (replacing the non-working part):

 // Create an empty object var newStyle = { }; // Add a dynamically named field newStyle[cssProperty] = moveTo; // Start the animation $(this).animate(newStyle, 1000); 
0
source

I found this solution great, but when I tested in Internet Explorer - unfortunately, it did not work. Reset Error: "The expected identifier, string, or dynamic property number of Internet explorer." So I made the less elegant decision of creating an animated call for each condition, making sure that the queue was set to false, because it should be executed simultaneously and applied to the same element that contained a different animation. For instance:

 if (directionX == "right"){ $(this).animate({"right": amountX},{duration: 600, queue: false}); } else if (directionX == "left"){ $(this).animate({"left": amountX},{duration: 600, queue: false}); } if (directionY == "top"){ $(this).animate({"top": amountY},{duration: 600, queue: false}); } else if (directionY == "bottom"){ $(this).animate({"bottom": amountY},{duration: 600, queue: false}); } $(this).animate({ "backgroundSize": bigWidths_array[itemNum], "width": bigWidths_array[itemNum], "height": bigHeights_array[itemNum]}, 600, false, showBigText(itemNum)); 
0
source

Source: https://habr.com/ru/post/1307768/


All Articles