Pages

Thursday, January 23, 2014

Simple javascript loading snippet

For now I`m facing a lot of situations when I need to load a content of some dynamic element in a page with ajax call. Something like this:
<div id="contentArea"></div>
<button onclick="load()" value="Load content" />
<script>
    $('#contentArea').load("url_to_load");
</script>

It is fine but sometimes I have to access database on a server side to load data and this operation can take some time... So I`ve googled a little and found (here) the simplest way to show loading animation with css. Probably, this snippet is more for myself - to not google for it once again but in the end I have something like this:
<style>
    .loading:after {
        border-width: 0 3px 0 0;
        border-style: solid;

        border-color: rgba(0, 0, 0, .5);
        border-radius: 50%;
        display: block;
        height: 50px;
        left: 50%;
        position: absolute;
        top: 50%;
        width: 50px;

        content: "";

        animation: spin 1s infinite linear;
        -webkit-animation: spin 1s infinite linear;
    }
    @keyframes spin {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }
    @-webkit-keyframes spin {
        from { -webkit-transform: rotate(0deg); }
        to { -webkit-transform: rotate(360deg); }
    }
</style>

<script>
    $('#contentArea').html("<div class='loading'></div>");

    $('#contentArea').load("url_to_load");
</script>

No comments:

Post a Comment