Created
January 3, 2014 05:18
-
-
Save ddneat/8233188 to your computer and use it in GitHub Desktop.
loading background images with a fadein effect by using jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// style.css | |
#bg-loading-parent{ | |
position: relative; | |
width: 100%; | |
height: 100%; | |
} | |
.bg-loading-container{ | |
display: none; | |
position: absolute; | |
top: 0; | |
right: 0; | |
bottom: 0; | |
left: 0; | |
} | |
// you may use a no-js class just to ensure, that all users get a background-image, | |
// even if they access your website without javascript. | |
// if you are not familiar with this technique visit http://modernizr.com/ | |
// and http://en.wikipedia.org/wiki/Unobtrusive_JavaScript | |
.no-js #bg-loading-parent{ | |
background-image: url(image.jpg); | |
background-size: cover; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// yourjquery.js | |
$(function() { | |
$parentContainer = $('#bg-loading-parent'); | |
// ensure parentContainer exists | |
if ($parentContainer.length) { | |
// also have a look at this http://css-tricks.com/snippets/jquery/fixing-load-in-ie-for-cached-images/ | |
$('<img/>').attr('src', 'image.jpg').load(function() { | |
// remove obsolete element | |
$(this).remove(); | |
// generate a dom element, which will render our background-image | |
// make sure you add the bg-loading-container class also in your stylesheet | |
$parentContainer.prepend('<div class="bg-loading-container"></div>'); | |
// the image is still cached in the browser, so there wan't be a second http-Request | |
// if you're not familiar with jquery, you may check the jquery documentation for | |
// some fadeIn attributes like duration and easing: http://api.jquery.com/fadein/ | |
$parentContainer.children('.bg-loading-container').css('background-image', | |
'url(image.jpg)').css('background-size','cover').fadeIn(); | |
}); | |
} else { | |
// dont forget to delete this log | |
console.log('the parent container does not exist.'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment