user1845888
user1845888

Reputation: 21

How do you make text fade in and out automatically with jQuery?

I am having some troubles; I want this line of text to fade in and out automatically when the page loads. But right now its not doing anything, is there something I am missing?

Here is my code, I was recently looking at previous stackoverflow posts that are similar to this topic, but I just can't get it to work.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New Web Project</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script src="js/jquery-1.6.3.min.js"></script>
<script src="fancybox/jquery.fancybox-1.3.4.js"></script>
<script>
  $(document).ready(function()
  {
    function fade(element)
    {
      var op = 1;
      // initial opacity
      var timer = setInterval(function()
      {
        if (op <= 0.1)
        {
          clearInterval(timer);
          element.style.display = 'none';
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op -= op * 0.1;
      }, 50);
    }//closes function

  });
  //closes document.ready function
</script>
</head>
<body>
<div id="fade" style="background-color:#66FFFF;width:500px;
height:100px;text-align:center;">
  <br />
  "This text should fade in and out"
</div>
<br />
<br />
</body>

Upvotes: 0

Views: 6451

Answers (2)

emgee
emgee

Reputation: 520

You can also simplify your code (unless you want to use your own fade logic) by using fadeToggle().

$(document).ready(function(){
    setInterval(function(){
        $("#fade").fadeToggle(400);
    }, 1500);
});

Assuming you really want it acting like a blink tag! :-)

Check out Fiddle

Upvotes: 1

Emin
Emin

Reputation: 270

I think you forgot to call the method at the end of initialization. Add:

     fade($("#fade"));

Upvotes: 1

Related Questions