1

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

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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');
  }
 })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.