Home > Software design >  Image toggling working only for one id on live website
Image toggling working only for one id on live website

Time:04-22

I have a limited js/jquery knowledge and I'm having a hard time figuring out why I am not able to make the following setup work on a live website; the second image doesn't toggle there.

It does work on Fiddle tho: https://jsfiddle.net/05vkw2mj/2/

#HTML

<div id="rodrigo">
RODRIGO

<img src="https://ywamsantiago.com/wp-content/uploads/2020/04/MG_1218-Rodrigo-Oliveira-copy-web-ready-500x500.jpg" id="rodrigo-img"/></div>

<div id="bob">
BOB

<img src="https://ywamsantiago.com/wp-content/uploads/2020/04/MG_1218-Rodrigo-Oliveira-copy-web-ready-500x500.jpg" id="bob-img"/></div>

#JQUERY

  $(document).ready(function() {
    $("#rodrigo").hover(function() {
      $("#rodrigo-img").toggle();
    });

    $("#bob").hover(function() {
      $("#bob-img").toggle();
    })
  });

#CSS

body {
  padding-top:400px;
}
#rodrigo {
  position: relative;
}
#rodrigo-img {
  display: none;
  position: absolute;
  bottom: 25px;
  left:0;
  width: 350px;
  max-width: 100%;
}

#bob {
  position: relative;
}
#bob-img {
  display: none;
  position: absolute;
  bottom: 25px;
  left:0;
  width: 350px;
  max-width: 100%;
}

CodePudding user response:

I think this may be a little easier to follow.

$(document).ready(function() {
  $(".links").hover(function(e) {
    $($(e.target).data().img).toggle();
  });
});
.img-container {
  position: relative;
  width: 150px;
  height: 150px;
  overflow: hidden;
}

.img-container img {
  position: absolute;
  display: none;
}

.links {
  display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <img src="https://picsum.photos/id/1020/300" id="rodrigo-img" />
  <img src="https://picsum.photos/id/1/300" id="bob-img" />
</div>
<div id="rodrigo"  data-img="#rodrigo-img">
  RODRIGO
</div>
<div id="bob"  data-img="#bob-img">
  BOB
</div>

  • Related