Creating A Loading Screen That Disappears After X Time On Button Click
I was wondering if it was possible to add a 'loading screen' that could be an overlay that shows up when a user clicks on specific link on my site. External links that will take th
Solution 1:
Check the following example using setTimeout
to waiting 2 seconds before opening the external link :
$(function(){
$('body').on('click', '#external-link', function(e)
{
e.preventDefault();
var link = $(this).attr('href');
$('body').append(
'<div id="overlay">' +
'<img id="loading" src="http://bit.ly/pMtW1K">' +
'</div>'
);
setTimeout(function(){
$('#overlay').remove();
window.open( link );
}, 2000); //2 seconds
});
})
#overlay {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
background: #000;
opacity: 0.8;
filter: alpha(opacity=80);
}
#loading {
width: 50px;
height: 57px;
position: absolute;
top: 50%;
left: 50%;
margin: -28px 0 0 -25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.com" id="external-link">External link</a>
Solution 2:
This can be done without relying on jQuery or any 3rd party libs. Wire up an event listener on your external links, apply a loading overlay and use a setTimeout()
to insert your artificial delay.
var delay = 2000;
var els = document.getElementsByClassName('external-link');
var loader = document.getElementById('loading');
for(var i = 0;i < els.length;i++){
els[i].addEventListener('click', function(e) {
var source = e.target || e.srcElement;
e.preventDefault();
loader.className = loader.className.replace('hidden', '');
setTimeout(function() {
window.open(source.href);
loader.className += 'hidden';
}, delay);
}, false);
}
.hidden {
display:none;
}
.loader {
position:fixed;
height:100%;
width:100%;
background-color: grey;
opacity:0.5;
}
.loader-text {
position:fixed;
top:45%;
left:45%;
}
<div class="loader hidden" id="loading">
<span class="loader-text">Loading...</div>
</div>
<div>
Website Content
<a href="http://google.com" class="external-link">Click me!</a>
<a href="http://yahoo.com" class="external-link">Or me!</a>
</div>
jsFiddle: http://jsfiddle.net/sysnull/t93ydLgy/3/
Post a Comment for "Creating A Loading Screen That Disappears After X Time On Button Click"