<div class="fade-in">Fade In & Out With CSS</div>
<div class="fade-in-js">Fade In & Out With CSS</div>
div {
    width: 100px;
    height: 100px;
    background-color: orange;
    margin: 20px;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes fadeOut {
    from { opacity: 1; }
    to { opacity: 0; }
}


.fade-in {
    animation: fadeIn 2s forwards;
}

.fade-in:hover {
    animation: fadeOut 2s forwards;
}
// Add the @keyframes if not present in CSS
let styleSheet = document.styleSheets[0];
let fadeIn = `
    @keyframes fadeIn-JS {
        from { opacity: 0; }
        to { opacity: 1; }
    }
`;
let fadeOut = `
    @keyframes fadeOut-JS {
        from { opacity: 1; }
        to { opacity: 0; }
    }
`;
styleSheet.insertRule(fadeIn, styleSheet.cssRules.length);
styleSheet.insertRule(fadeOut, styleSheet.cssRules.length);

const box = document.querySelector('.fade-in-js');

box.addEventListener('mouseover', function() {
    this.style.animation = 'fadeOut-JS 2s forwards';
});
box.addEventListener('mouseout', function() {
    this.style.animation = 'fadeIn-JS 2s forwards';
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.