Reputation: 6781
I want to make a simple transition but struggle doing it with jQuery. I create the element that is to be transformed in JS in an eventListener like so:
const searchHint = `
<h3 id="search_hint" class="invizible">
Enter a search term to continue!
</h3>
`
$('#search_label').append(searchHint)
$('#search_hint').removeClass('invizible').addClass('make_vizible')
In my stylesheet I've got those styles for the classes 'invizible' and 'make_vizible':
#search_hint.invizible {
color: white;
transition: color 1s ease;
}
#search_hint.make_vizible {
color: #404040;
}
As I understand, this should result in the search hint element slowly fading in. I create it with the invizible class, where a transition attribute is present and also a start value for the attribute to be transformed. Then I switch the classes, to a class with a different color value.
What happens, is that the element is just displayed, not animated.
Any ideas?
Upvotes: 0
Views: 202
Reputation: 14561
There are two issues:
The transition
property is set in invizible
class. So once you remove it, that property is not applicable. To resolve this, associate the transition
to the element id.
The removeClass
and addClass
are probably getting applied to the same frame that appends #search_hint
while rendering. To mitigate this you could wait for the frame to render, and then add/remove the class. I've done this using setTimeout
with timeout value zero.
const searchHint = `
<h3 id="search_hint" class="invizible">
Enter a search term to continue!
</h3>
`;
$('#search_label').append(searchHint);
setTimeout(function() {
$('#search_hint').removeClass('invizible').addClass('make_vizible');
},0);
#search_hint {
color: white;
transition: color 1s ease;
}
#search_hint.invizible {
color: white;
}
#search_hint.make_vizible {
color: #404040;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="search_label">
</div>
Upvotes: 5