I have a simple function for adding animations to an element: addAnimation().
The main issue I'm having is with the function it calls: updateAnimationProperties()
. This function takes up to 4 parameters and at least 3 of them will use the same word, such as:
updateAnimationProperties( name, element, 'animationName', nameStr );
the string name
is used 3 times. This is how it will be every time this function is called. Another example:
updateAnimationProperties( duration, element, 'animationDuration', durationStr );
duration
is repeated 3 times. So I want to make a function that takes the base word: name
or duration
and automatically concatenates the rest with a string. such as 'animation' + baseVariable
or baseVariable + 'Str'
.
I've tried using the window method like this:
function updateAnimationProperties( target, element, property ){
if( target === '' ){
element.style[ property ] = window[ target + 'Str' ];
}
else {
element.style[ property ] += ', ' + window[ target + 'Str' ];
}
}
But it doesn't seem to help. Any idea how I can reduce the number of parameters this function needs by using dynamic variables instead?
Below is the normal code with 4 parameters. I want to reduce these to possibly just 2 parameters.
//\ \ \ \ \ \ \ UPDATE ANIMATION PROPERTIES / / / / / / / / / / / / / / / / / /
function updateAnimationProperties( target, element, property, result ){
if( target === '' ){
element.style[ property ] = result;
}
else {
element.style[ property ] += ', ' + result;
}
}
/// / / / / / / UPDATE ANIMATION PROPERTIES \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \
//\ \ \ \ \ \ \ \ \ \ ADD ANIMATION / / / / / / / / / / / / / / / / / / / / / /
function addAnimation( element, nameStr, durationStr ){
element.classList.add( 'animation' );
var name = element.style.animationName,
duration = element.style.animationDuration;
updateAnimationProperties( name, element, 'animationName', nameStr );
updateAnimationProperties( duration, element, 'animationDuration', durationStr );
}
/// / / / / / / / / / ADD ANIMATION \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \
var p = document.querySelector( 'p' );
addAnimation( p, 'blur', '100s' );
/* \ \ \ \ \ \ \ \ \ \ \ \ \ ANIMATION DEFINITIONS / / / / / / / / / / / / / */
.animation {
animation-duration: 1s;
animation-delay: 0s;
animation-iteration-count: 1;
animation-timing-function: ease;
animation-direction: normal;
animation-fill-mode: forwards;
animation-play-state: running;
}
.blur {
animation-name: blur;
}
/*\ \ \ \ \ \ \ \ \ \ \ \ \ \ ANIMATION KEYFRAMES / / / / / / / / / / / / / /*/
@keyframes blur {
100% {
filter: blur( 5rem );
}
}
<p>Blur this paragraph</p>