views:

70

answers:

3

Hi everyone!

I'm trying to make some code which finds if a div exists, and if it does then have it fade away slowly. I have this to determine whether or not the div exists

    if($('#error').length != 0)
 {
  $('#error').hide(500);
 }  

And that does work but only on a refresh, I've been attempting to put it in a timer like this:

   var refreshId = setInterval(function()
   {
      if($('#error').length != 0)
 {
  $('#error').hide(500);
 }   
   }, 500);

But its not getting rid of the innerHTML! I have some code which on hover alters the innerHTML of the error div so I can fill it up, but for some reason this isn't working, any advice would help!

Thank you!

+3  A: 
$("#error").fadeOut(500);

Update:

If you are looking to check for existence:

var msg = $("#error");
if(msg.length) {
  msg.fadeOut(500);
}

If you want to empty it:

$("#error").empty();
sworoc
You should never need to check for existence like this...
Nick Craver
Oh, I agree. However, in his statement he is checking for existence which may or may not be used elsewhere in his program for other reasons. Thought I might as well add it, in general I recommend just using the first line.
sworoc
+5  A: 

If you just want to delay 500ms then fade out, do this:

$("#error").delay(500).fadeOut();

To also empty the element, provide a callback to .fadeOut() like this:

$("#error").delay(500).fadeOut(function() {
  $(this).html('');
});

There's no need to check .length, if an element that matches the selector isn't present, nothing happens :)

Nick Craver
A: 

The div you're trying to hide likely hasn't loaded by the time your script runs. Try this; it will defer execution until the DOM is loaded:

 $(document).ready(function() {
   // put your code here
 });

This is a good practice when using jQuery anyway.

Reference: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

Nick