Fade in out in loop

I have got the following code which works (almost) fine

Here is my div

<div id="message" style="display:none;">Hello!</div>

And this code which will show if after 5 seconds and make it disappear after 20:

 $( document ).ready(function(){
            $('#message').delay(5000).fadeIn('slow', function(){
               $('#message').delay(20000).fadeOut(); 
            });
    });

What I want to do is doing this in a loop, in other words fadein after 5sec, fadeout after 20sec, fadein after 5, fadeout after 20, etc

Any idea ?

I recommend moving the code out to a separate named function, so that you can use setInterval to make it run on a regular basis.

Alternatively, give your $(document).ready() callback a name so you can again pass it to fadeOut() as the complete callback.

Hi there Corobori,

this task should really be done with CSS rather than with JQuery. :eek:

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<!--<link rel="stylesheet" href="screen.css" media="screen">-->

<style media="screen">

body {
    background-color: #f9f9f9;
    font: 100% / 162% BlinkMacSystemFont, -apple-system, 'Segoe UI', roboto, helvetica, arial, sans-serif;
 }

h1 {
    animation: fadeIn 25s ease-in-out infinite;
 }

@keyframes fadeIn {
  0% { opacity:0; }
 10% { opacity:1; }
 90% { opacity:1; }
100% { opacity:0; }
 }

</style>

</head>
<body> 

 <h1>Lorem Ipsum</h1>

</body>
</html>

coothead

3 Likes

Thanks Paul.

I am trying this and it seems to work

    setInterval(function() {
            $('#message').delay(5000).fadeIn('slow', function(){
               $('#message').delay(15000).fadeOut(); 
            });
    }, 20000);

Thank you, I’ll have a look into it. I prefer doing in CSS too but knowing both ways doesn’t make it any harm.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.