vemund
vemund

Reputation: 1807

Script with lightbox only runs once

I'm trying to make a lightbox function that fades in when clicked on link. I can run it once. When it has been ran and then closed, it can not be ran again? Kind of weird? What did I do wrong?

My script:

<script>
   $(document).ready(function() {
           $('.button1').click(function() {
                  $('#aloe').fadeIn(600);
          });
   });
</script>

Code:

<a class="button1"><img src="{{ 'aloevera.png' | asset_url }}" /></a>


<div id="aloe" style="display: none;"><div id="box1">
          <div id="inner"><a class="exit" onclick='$("#box1").fadeOut(600, function() { $(this).remove(); });'>x</a>
          </div>
        <div class="outer">
          <div class="middle">
            <div class="inner">
              <h1>Organic Aloe Vera Extract</h1>
              Our organic Aloe Vera Extract is from Asia. The polysaccharides act as moisturizers and hydrate the skin. 
              Aloe vera is absorbed into the skin and stimulates the fibroblasts to replicate themselves faster and it 
              is these cells that produce the collagen and elastin fibers, so the skin becomes more elastic and less wrinkled.
            </div>
          </div>
        </div>
    </div></div>

Upvotes: 0

Views: 64

Answers (2)

lonesomeday
lonesomeday

Reputation: 237905

It's because you remove the element after fading it out, so it can't be shown again:

$("#box1").fadeOut(600, function() { $(this).remove(); })

Note that doing JS in inline attributes is a bad idea. Put it in your ready handler and get rid of the remove call. You also probably want to fade #aloe out, rather than #box1:

$(document).ready(function() {
   $('.button1').click(function() {
       $('#aloe').fadeIn(600);
   });

   $('.exit').click(function() {
       $('#aloe').fadeOut(600);
   });
});

Demonstration of working code

Upvotes: 1

Tommy Ivarsson
Tommy Ivarsson

Reputation: 605

When you exit using remove() you are removing #box1 from the DOM. That means it doesn't exist when you try to fade it in the second time. Use hide() instead as that only sets a CSS-attribute to hide the container from view instead of removing it from the DOM.

Upvotes: 1

Related Questions