how to define a background-image in src of an img tag using jquery?

Asked

Viewed 116 times

1

I’m creating a modal to display a gallery and the idea is that when clicked on the images, the modal looks in the background-image of each <img> and apply to src. The modal works, but the image doesn’t appear because the src is empty and I can’t make the crease. I’ve tried several methods and I couldn’t get any results. Each <img> has an ID, and each ID has its background-image. The structure looks like this:

$('.img').click(function(evento){
    var imagem = evento.target.src;
    
    var modal = '<div id="modal"><img src="'+ imagem + '" class="modalImagem"><div id="btFecha">X</div></div>';

$('body').append(modal);

})
#i1 {
  background-image: url(../_img/ilustracao001.jpg);
}
#w1 {
  background-image: url(../_img/web001.jpg);
}
#d1 {
    background-image: url(../_img/dg001.jpg);
}
<div class="menuPort">
  <ul id="galeria">
    <li><img id="i1" class="img ilustra" src=""></li>
    <li><img id="w1" class="img wd" src=""></li>
    <li><img id="d1" class="img dg" src=""></li>
  </ul>
</div

Someone knows what I have to do to make it work?

1 answer

0


You want to catch the background-image css. Do this:

$('.img').click(function(){
    var imagem = $(this)
	.css('background-image')
	.replace("url(","")
	.replace(")","")
	.replace(/"/g, "");
    var modal = '<div id="modal"><img src="'+ imagem + '" class="modalImagem"><div id="btFecha">X</div></div>';

$('body').append(modal);

})
#i1 {
  background-image: url(http://cinebsb.tempsite.ws/i/poster/fil_201772314241.jpg);
}
#w1 {
  background-image: url(http://cinebsb.tempsite.ws/i/poster/fil_20177271029.jpg);
}
#d1 {
    background-image: url(http://cinebsb.tempsite.ws/i/poster/fil_20177221461.jpg);
}

li img{display:block;width:100px;height:50px;}

#modal{
	display: block; width: 100px; height: 200px; position: absolute; border: 1px solid #ddd;top:0; right: 180px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menuPort">
  <ul id="galeria">
    <li><img id="i1" class="img ilustra" src=""></li>
    <li><img id="w1" class="img wd" src=""></li>
    <li><img id="d1" class="img dg" src=""></li>
  </ul>
</div>

  • THAT!!! David, I have more than 1 month in this search and research to solve this. Thanks!! Pass me where you learned it please because I need to learn more.

  • Thanks! Dude, we learn by reading and searching on the net. A good place where you can learn mts things is at https://www.w3schools.com/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.