When it comes to loading different images onto an "img" tag by printing their URLs using JavaScript and then letting CSS manipulate the content in the tag, I have a code snippet that does just that.
$(window).load(function() {
var randomImages = ['img1','img2','img3','img4','img5','img6','img7','img8','img9','img10','img11','img12','img13','img14','img15','img16','img17','img18','img19','img20','img21','img22','img23','img24','img25','img26','img27','img28','img29','img30'];
var rndNum = Math.floor(Math.random() * randomImages.length);
var $win = $(this);
var iMac = $(window).width() > 1920 ? '_imac' : '';
var $img = $('#background').attr('src', '_img/bg/index_rnd/' + randomImages[rndNum] + iMac + '.jpg').css({'position':'fixed','top':0,'left':0});
function resize() {
if (($win.width() / $win.height()) < ($img.width() / $img.height())) {
$img.css({'height':'100%','width':'auto'});
} else {
$img.css({'width':'100%','height':'auto'});
}
}
$win.resize(function() { resize(); }).trigger('resize');
});
I am currently working on a new website project and would like to implement a similar system where I select an image from an array and apply its URL as a background image via CSS for the #home element.
#home{
background: url(INSERT URL OF JAVASCRIPT HERE) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
I attempted to achieve this functionality but feel like my approach is not optimal. I'm not entirely sure if what I want to do is even possible without using JavaScript or if there's a simpler way that I may be overlooking due to lack of expertise.
$(window).load(function() {
var randomImages = ['img1','img2','img3'];
var rndNum = Math.floor(Math.random() * randomImages.length);
var url = 'url(_img/bg_array/' + randomImages[rndNum] + '.jpg)'
$('#home').css({
'background:' url 'no-repeat' 'center' 'center' 'fixed',
'-webkit-background-size': 'cover',
'-moz-background-size': 'cover',
'-o-background-size': 'cover',
'background-size': 'cover'
});
}
Thank you for any help!
EDIT: MORE INFO //////////////////////////////