0

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?

JackDonMcLovin
  • 137
  • 2
  • 11
  • Give `fadeIn` a duration. `fadeIn(2000)` for example to make it fade in over 2 seconds. – Taplar Dec 24 '19 at 18:46
  • https://jsfiddle.net/cxfthsLu/ your existing logic works for me. giving the fadeIn a duration makes it more pronounced, but it works without it. I cannot replicate your issue. – Taplar Dec 24 '19 at 18:55

2 Answers2

1

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>
Shiny
  • 4,945
  • 3
  • 17
  • 33
  • I don't believe the ids are duplicated. i believe the OP is presenting two different snippets, saying the first works and the second one does not – Taplar Dec 24 '19 at 18:47
  • Perhaps, but from the snippet he provided this is the issue I saw - And being as I changed no other code and it worked okay, and no *other* code was provided, it seems reasonable to suggest this as the solution – Shiny Dec 24 '19 at 18:58
  • Or simply make a quick comment of, "Are you doing both of these snippets at the same time?" to confirm first. :) – Taplar Dec 24 '19 at 18:59
1

Using simple CSS is easy.

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

.box.hidden {
  opacity: 0;
}
Tom Shaw
  • 1,642
  • 2
  • 16
  • 25