jquery – Hide image on click-ThrowExceptions

Exception or error:

I’ve been trying to hide an image on click so that I can click tag to show it and hide it

I tried many codes but it didn’t work for me.
Every time I click the image keeps adding to the page

<body>
 <a href="#" class="nebulae">nebulae</a>
<div class="col-md-4 first"></div>
<body>

$('.nebulae').click(function(e) {
    const img = '<img src="nebulae.jpg" class="rounded float-left">';
    $('<img src="nebulae.jpg" class="rounded float-left">').appendTo(".first");
    if(img) {
        $('html, body').animate({
            scrollTop: $(".first").offset().top
        }, 1000);
    }else{
    }
})

I tried this

if(img) {
        $('html, body').animate({
            scrollTop: $(".first").offset().top
        }, 1000).on( "click", $(this).find( $(this) ));
    }else{
        $('html, body').animate({
            scrollTop: $(".first").offset().top
        }, 1000).off( "click", $(this).hide( $(this) ));
    }

but does not work either

How to solve:

I will recommend, don’t load image again & again. Put that image inside div in HTML and just show/hide at button click

 <body>
   <a href="#" class="nebulae">nebulae</a>
   <div class="col-md-4 first">
    <img src="nebulae.jpg" class="rounded float-left" />
   </div>
 <body>


$('.nebulae').click(function(e) {
 if($(this).hasClass('active')){
    $(".first").hide();
    $(this).removeClass('active');
  }
  else{
     $(".first").show();
      $('html, body').animate({
        scrollTop: $(".first").offset().top
    }, 1000);
    $(this).addClass('active');
  }
 })

//or if you have to load image after click event

 <body>
   <a href="#" class="nebulae">nebulae</a>
   <div class="col-md-4 first">

   </div>
 <body>


$('.nebulae').click(function(e) {
 if($(this).hasClass('active')){
    $(".first").html('');
    $(this).removeClass('active');
  }
  else{
     $(".first").html('<img src="nebulae.jpg" class="rounded float-left" />');
      $('html, body').animate({
        scrollTop: $(".first").offset().top
    }, 1000);
    $(this).addClass('active');
  }
 })

###

Easiest way to make an image show or hide based on clicking another element in the DOM is by doing the below. Give it a try.

$(".nebulae").on("click", function () {
  $(".first").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="nebulae">nebulae</a>
<div class="col-md-4 first">
  <img src="https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png" />
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *