JackDonMcLovin
JackDonMcLovin

Reputation: 177

jQuery fadeOut works, fadeIn no error, no change, similarly fadeToggle doesn't come back on

This is driving me batty... this works fine:

<div id="box"> 
    <img src="/images/wpgen_box1.jpg">
</div>
<script type="text/javascript">
    jQuery(document).ready(function(){
        setTimeout(function(){ jQuery('#box').fadeOut(); }, 5000);
    });
</script>

But this does NOT work:

<div style="display:none" id="box">
    <img src="/images/wpgen_box1.jpg">
</div>
<script type="text/javascript">
    jQuery(document).ready(function(){
        setTimeout(function(){ jQuery('#box').fadeIn(); }, 5000);
    });
</script>

So, anyone know why I can fade out but not in?

Upvotes: 0

Views: 58

Answers (2)

Shiny
Shiny

Reputation: 5055

Looks like it was an issue of your IDs being the same for both elements - IDs should be unique

Here is a link to a post talking about this 'issue':

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid

$(document).ready(function() {
  setTimeout(() => $('#box').fadeOut(), 5000);
});

$(document).ready(function() {
  setTimeout(() => $('#box2').fadeIn(), 5000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="box">
  <img src="https://via.placeholder.com/250?text=I am visible">
</div>

<div style="display:none" id="box2">
  <img src="https://via.placeholder.com/250?text=I was invisible">
</div>

Upvotes: 1

Tom Shaw
Tom Shaw

Reputation: 1712

Using simple CSS is easy.

.box {
  opacity: 1;
  transition: opacity .25s ease-in-out;
}

.box.hidden {
  opacity: 0;
}

Upvotes: 1

Related Questions