Kategorien
Code

Loading Indicator á la Youtube mit CSS

Loading-Balken
Der Plan

Nachdem ich eine vernüftige Ladeanimation gesucht habe, und bei allem immer irgendwie jQuery dranhängen musste, hab ich beschlossen, das ganze mal in lean zu lösen. Probleme dabei gibt es eigentlich nur im Bereich des Animationsstarts durch JS, dazu habe ich bei CSS-Tricks den passenden Tipp gefunden.

HTML:

<div class="loading-bar"></div>

CSS:

    .loading-bar {
        display: none;
        opacity: 0;
        position: absolute;

        top: 0;
        width: 100%;
        max-width: 100%;
        margin: 0;
        padding: 0;

        background: red;
        height: 0;
        animation-name: expand-width, fade;
        animation-duration: 1s, 4s;
        animation-delay: 0s, 1s;

        animation-iteration-count: 1;
    }

    .loading-bar.visible {
        display: block;
        opacity: 1;
        height: 2px;
    }

    @keyframes fade {
        from {
            height: 2px;
            opacity: 1;
        }
        to {
            height: 0;
            opacity: 0;
        }
    }

    @keyframes expand-width {
        from {
            width: 0;
        }
        to {
            width: 100%;
        }
    }

    @keyframes glow {
        from {
            box-shadow: 0 0 5px red,
            0 0 10px red,
            0 0 10px rgba(255, 165, 0, 1),
            0 0 20px rgb(255, 244, 0);
        }
        to {
            box-shadow: none;
        }

    }

    .loading-bar.visible:before {
        box-shadow: none;

        position: absolute;
        right: 0;
        content: "";
        display: block;
        height: 2px;
        width: 8px;
        animation-name: glow;
        animation-duration: 5s;
        animation-iteration-count: 1;
    }

 

Javascript:

    var links = document.querySelectorAll( 'a' ),
            linkslen = links.length;

    for ( var link = 0; link < linkslen; link++ ) {

        links[link].addEventListener( 'click', function ( e ) {
            var lb = document.querySelectorAll( '.loading-bar' )[0];
            lb.classList.remove( 'visible' );
            //noinspection SillyAssignmentJS
            // triggers reflow for animation restart
            lb.offsetHeight = lb.offsetHeight;
            lb.classList.add( 'visible' );
        }, false )
    }

Edit am 29.12.: Ich habe den Code mal ein bisschen lesbarer und einfacher gemacht. Dazu habe ich das innere DIV entfernt, dass CSS zusammengeführt und das JS ein bisschen lesbarer gemacht. Mein Partial aus meinem Hugo-Projekt habe ich mal als Gist online gestellt. Sichergestellt sein sollte, dass das Partial so eingefügt wird, dass .loading-bar direktes Kind-Element von BODY ist. Ansonsten müssen ggf. die Styles angepasst werden.

Von Chris Jung

Ich bin Entwickler bei basecom und erstelle nebenberuflich kleine Websites für kleine Unternehmen und Privatpersonen. Ich bin Open Source Fan und Blogger.

Portfolio . twitter . github