Home > Software design >  Javascript - Show and Add image based on date
Javascript - Show and Add image based on date

Time:11-25

I would like to create a landing page where I gradually show our winnings for the advent calendar. For this I have prepared images, which will then be revealed in a DIV.

So until 01 December you will not see any pictures. On 01 December one sees then picture 01 On 02. December one sees picture 01 & picture 02 and so on

I have found the following code so far. Unfortunately only the DIV with today's date is shown to me. What do I have to do so that the images stay with?

Here is my fiddle: https://jsfiddle.net/bkoenig/m2pzqjrs/14/

<div >
    1
</div>

<div >
    2
</div>

<div >
 3
</div>
var now = new Date().toDateString();
var october1 = new Date("November 22, 2022").toDateString();
var october2 = new Date("November 23, 2022").toDateString();
var october3 = new Date("November 24, 2022").toDateString();


if(now != october1) // today is after Christmas
{
     // an id of a div that holds your images?
     $('#div_id').hide(); 
     // or a class of images
     $('.image1').hide();
}


if(now != october2) // today is after Christmas
{
     // an id of a div that holds your images?
     $('#div_id').hide();
     // or a class of images
     $('.image2').hide();
}

if(now != october3) // today is after Christmas
{
     // an id of a div that holds your images?
     $('#div_id').hide();
     // or a class of images
     $('.image3').hide();
}

.imageClass {
        display: ;
    }

CodePudding user response:

I have an example for your problem, hope it helps you

(function () {
  const now = new Date();
  $("#imageDate img").each(function () {
    const el = $(this);
    const date = new Date(el.attr('data-date'));
    console.log(now, date)
    if (date <= now) {
      el.show();
    }
  });

})();
#imageDate img {
  display: none;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imageDate">
  <img src="" data-date="November 22 2022" alt="22/11/2022" />
  <img src="" data-date="November 23 2022" alt="23/11/2022" />
  <img src="" data-date="November 24 2022" alt="24/11/2022" />
</div>

  • Related