Can't select changed image src with jquery

Viewed 41

I've changed img src via jquery, but now I want to open a modal when you click on image, and for some reason I can't select the changed img, when I click on it the action goes to the image before the src change. Heres my code:

HTML:

        <div class="tipoplantas text-center">
            <button id="botao2" type="button" class="botaoplantas">1</button>
            <button id="botao1" type="button" class="botaoplantas">2</button>
        </div>
        <div class="imagemplanta text-center">
            <img id="imagemplanta" src="img/infinity/planta1.jpg" class="img-fluid">
        </div>

JAVASCRIPT:

    // Switch Images

    $('#botao1').click(function(){
      $('#imagemplanta').each(function(){
         $(this).animate({
           opacity: 0
         }, 500, function(){
          $('#botao1').addClass('selected')
          $('#botao2').removeClass('selected')
            $(this).attr('src', '/img/infinity/planta1.jpg');
         });
        $(this).animate({
          opacity: 1
        }, 500);
      });
   });
    $('#botao2').click(function(){
      $('#imagemplanta').each(function(){
         $(this).animate({
           opacity: 0
         }, 500, function(){
            $('#botao2').addClass('selected')
            $('#botao1').removeClass('selected')
            $(this).attr('src', '/img/infinity/planta2.jpg');
         });
        $(this).animate({
          opacity: 1
        }, 500);
      });
   });

   // Test
   $("img[src$='img/infinity/planta2.jpg']").click(function() {
    alert('234');
  })
  $("img[src$='img/infinity/planta1.jpg']").click(function() {
    alert('123');
  }) 

So whenever I change to the 2nd image and click on top it sends the alert "123" instead of the "234" which is what I want.

1 Answers

you can do that

$('#imagemplanta').click(function()
  {
  let imgSrc = $(this).attr('src')
    , imgIdx = imgSrc.lastIndexOf("/") + 1
    , imgName = imgSrc.substr(imgIdx)
    ;
  if (imgName === 'planta1.jpg')  alert('123')
  else                            alert('234')
  })
Related