I am trying to make jQuery dynamically change the background image by pulling the src attribute from the image tag (img#backSwitch) on the page (which i will make randomly pull from an array in php later), and change the div.background-image element's background-image property value to whatever the src attribute's value is. my console.log is working just fine, i would like to think what i am doing in jQuery is fine as well, but clearly I'm doing something wrong or overlooking a mistake that isn't showing an error. Any help would be great!
Here is my HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="background-image"></div>
<div class="content">
<img src="img/ped4.jpg" id="backSwitch" alt="Pedestal" />
</div>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/js.js"></script>
</body>
</html>
HERE IS MY jQuery
(function() {
var backSwitch = $('#backSwitch').attr('src'),
theURL = 'http://staging.youknowphabo.com/';
$('.background-image').css({backgroundImage: 'url('+theURL+backSwitch+');'});
console.log(theURL+backSwitch);
})();
HERE IS MY CSS
@import url(//fonts.googleapis.com/css?family=Roboto+Slab:400);
.background-image {
position: fixed;
left: 0;
right: 0;
z-index: 1;
display: block;
background-image: url('http://666a658c624a3c03a6b2-25cda059d975d2f318c03e90bcf17c40.r92.cf1.rackcdn.com/unsplash_527bf56961712_1.JPG');
width: 100%;
height: 100%;
text-align: center;
margin: 0 auto;
background-size: cover;
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
}
.content {
position: relative;
z-index: 999;
}
.content img {
width: 100%;
max-width: 600px;
padding: 30px;
display: block;
text-align: center;
margin: 0 auto;
}
I think the problem is a typo:
$('.background-image').css({backgroundImage: 'url('+theURL+backSwitch+')'});
Try removing the semicolon from the CSS url property.
You could also write it like this:
$('.background-image').css({'background-image': 'url('+theURL+backSwitch+')'});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.