I have a series of images setup like the below:
<img src="abc.jpg" class="change-img">
<img src="def.jpg" class="change-img">
<img src="ghi.jpg" class="change-img">
I have a separate div elsewhere with a background image set inline such as:
<div class="change-me" style="background-image:url('xyz.jpg');background-size:100%;">
I am wondering how I could work some jQuery code to change the background image URL dynamically, based on the img clicked.
So the ideal situation would be if you click on image abc.jpg it will put abc.jpg into the background-image property of the change-me class.
Here is the start of my jQuery I'm messing with:
jQuery('.change-img').on('click', function() {
var img = jQuery(this).attr('src');
jQuery('.change-me').css('background-image', img);
});
It doesn't work, so it would be great for someone to assist and lead me in the right direction! Thanks so much in advance
Edit: Just tried to alter how img is being displayed but still no luck, it works if i put 'none' in there, so i think the issue lies with not detecting the src of the image clicked properly.
jQuery('.change-img').click(function() {
var img = jQuery(this).attr("src");
jQuery('.change-me').css("background-image", "url:('" img "');");
});
CodePudding user response:
url(http://...)
, there is no colon after url
jQuery('.change-img').click(function() {
const img = jQuery(this).attr("src");
jQuery('.change-me').css("background-image", "url('" img "')");
});
img { width: 100px; height: 100px; }
.change-me { width: 120px; height: 120px; border: 1px solid #eee; }
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<img src="https://cdn.sstatic.net/Img/company/awards/appealie-saas-awards.png?v=30b5fc47c566" class="change-img">
<img src="https://cdn.sstatic.net/Img/company/awards/g2.svg?v=8416c53d06c8" class="change-img">
<img src="https://cdn.sstatic.net/Img/company/awards/remotetechbreakthrough.svg?v=3979e85e4b0b" class="change-img">
<div class="change-me"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>