My solution:
I changed the display
styles to visibility
styles because this solution suited my webpage best. Many other solutions can be found by Googling "display block overrides animation". The accepted answer is the one that gave me the keywords so I could use Google.
Original post:
I've made fadeIn
and fadeOut
functions to animate the opacity using CSS animations rather than JQuery animations.
Clicking on the image should make a popup fade in and the image fade out over 300ms.
Clicking anywhere in the body should make the popup fade out and the image fade in over 300ms.
At the moment the fadeOut works, but fadeIn seems to ignore the transition time, and instantly appears. Why isn't fadeIn working?
JavaScript:
function fadeIn(elem) {
elem.css("display", "block");
elem.css("opacity", 1);
}
function fadeOut(elem) {
elem.css("opacity", 0);
setTimeout(function() {
elem.css("display", "none");
}, 300);
}
$("body").on("click", function(ev) {
if (ev.target != $("#btn")[0] && $("#popup").is(":visible")) {
fadeIn($("#btn"));
fadeOut($("#popup"));
}
});
$("#btn").on("click", function(ev) {
fadeIn($("#popup"));
fadeOut($("#btn"));
});
CSS:
#btn {
position: absolute;
top: 100px;
left: 10px;
transition: 0.3s;
opacity: 1;
}
#popup {
position: absolute;
background-color: black;
display: none;
color: red;
z-index: 1;
padding: 0 1em;
transition: 0.3s;
opacity: 0;
}