DEV Community

Fajar Windhu Zulfikar
Fajar Windhu Zulfikar

Posted on • Originally published at fajarwz.com on

How to Solve Unwanted CSS Transitions on Page Load

Writing CSS illustration

There is a case where you need to add transitions to your page. Maybe you put it on some pages or even all pages. Then you noticed there is an unwanted transitions on page load.

Transitions Enabled Only After Page Load

We can fix that. The idea is to disable transitions in our page first then enable it after the page loaded.

First we can create a CSS class that disable transitions:

.no-transition * {
    -webkit-transition: none !important;
    -moz-transition: none !important;
    -ms-transition: none !important;
    -o-transition: none !important;
    transition: none !important;
}
Enter fullscreen mode Exit fullscreen mode

Then put it on body element:

<body id="body" class="no-transition">
Enter fullscreen mode Exit fullscreen mode

When the page loads, remove it:

function transitionAfterPageLoad() {
    document.getElementById("body").classList.remove("no-transition");
}

// call the function inside an Immediately Invoked Function Expression (IIFE) to invoke it immediately after page load
(function() {
    transitionAfterPageLoad();
})()

// jQuery 
$(function() {
    $("#body").removeClass("no-transition");
});
Enter fullscreen mode Exit fullscreen mode

That's it, easier than we think.

Conclusions

To fix unwanted CSS Transitions on page load we can disable transitions to our page first then re-enable it after the page loaded.

Have another tip or even a better one about this issue? Please let us know in the comments section below πŸ‘‡. Share this if you think this is helpful. Thank you.

Top comments (0)