Skip to content Skip to sidebar Skip to footer

How To Fade Out Django Success Messages Using Javascript Or Css?

I am trying to fade out Django success messages using a small Javascript script but cannot seem to get it to work. This is in my base.html: {% if messages %} {% for message in mess

Solution 1:

Django is only rendering your template, and return from a server side a HTML file which then need to be handled by your browser using CSS and javascript. An easy way to perform animation is using CSS transitions.

CSS Transitions

<divclass="alert alert-{{ message.tags }}">
    {{ message }}
</div>
.alert {
    positition: relative;
    opacity: 1;
    visibility: visible;
    transform: translateX(0px);
    transition: visibility 0s, opacity 250ms, transform 250ms;
}
.alert.hide {
    positition: relative;
    opacity: 0;
    visibility: hidden;
    transform: translateX(-10px); // translateX, translateY, translateZ works well
    transition: visibility 0s250ms, opacity 250ms, transform 250ms;
}

Then use Javascript to add a class to it:

<script>var m = document.getElementsByClassName("alert");  // Return an arraysetTimeout(function(){
   if (m && m.length) {
       m[0].classList.add('hide');
   }
}, 3000);
</script>

CSS animation library

This is the verbose version which consist of writting your own animation and configure exactly as you need, but a simple solution could be to use a CSS animation library like animate.css which provide a set of amazing transitions on the same principle.

Just be careful not using too much of them, you do not want your application to look like a christmas tree 🤣.

Post a Comment for "How To Fade Out Django Success Messages Using Javascript Or Css?"