0

I have following code:

HTML:

<div id="container">
    text text text
</div>

<img id="img1" src="img1.png" />
<img id="img2" src="img2.png" />

CSS:

#container {
    display: block;
    margin-top: 0vh;
    transition: margin-top 1s ease-in 0.1s, display 0.1s linear 5s ;
}

JS:

$("img#img1").on('click', function () {
    $("#container").css('margin-top', '50vh');
    $("#container").css('display', 'none');
});

$("img#img2").on('click', function () {
    $("#container").css('margin-top', '0vh');
    $("#container").css('display', 'block');
});

Looking on CSS file, my intention is:

  • margin-top property, change after 0.1 second, for 1 second
  • display property, change after 5 second, for 0.1s

But it doesn't work. The display property is changed immediately after click on image.

How to fix it?

Przemysław Niemiec
  • 1,704
  • 1
  • 11
  • 14

1 Answers1

-1

To add a delay in JavaScript, you can use the setTimeout function.

To add a five-second delay in your code, you would do the following:

$("img#img1").on('click', function () {
    $("#container").css('margin-top', '50vh');
    setTimeout(function() {
        $("#container").css('display', 'none');
    }, 5000);
});

$("img#img2").on('click', function () {
    $("#container").css('margin-top', '0vh');
    setTimeout(function() {
        $("#container").css('display', 'block');
    }, 5000);
});

The 5000 in this code is 5 seconds represented in millseconds. Hopefully the rest is self-explanatory - a function is specified which is executed after the set length of time.

Not quite sure what you mean about changing display for 0.1s though. An element is either displayed or it isn't - there is no in-between. If want something to fade, change its opacity instead. You probably ought to remove ", display 0.1s linear 5s" from your CSS too.

spacer GIF
  • 626
  • 5
  • 19
  • Whoever downvoted, please explain why. No JavaScript wasn't specified as a requirement and CSS transitions don't work on `display`. I did mention that the opacity can be changed if that's the desired effect, but that alone won't hide the element from the document without reserving space like `display` does. Of course, you could do a mixture of things such as fading an element and then setting `display` to `none` and vice-versa. – spacer GIF May 12 '18 at 22:14