Oscar
Oscar

Reputation: 105

Problem with setInterval

I have a problem with setInterval on a 'click' event. Im already spawning a hidden div. But I want spawn and fade in synced and only run the fade in ones.

 var anchor = document.getElementById('anchor');
                var hiddenElement = document.getElementById('hiddenElement');
                var bkgFade = document.getElementById('bkgFade');

                anchor.addEventListener('click', spawnImage, false);
                hiddenElement.addEventListener('click', despawnImage, false);
                function spawnImage() {
                     setInterval(function() {
                        document.getElementById('hiddenElement').style.display = 'block';
                        document.getElementById('bkgFade').style.visibility = 'visible';
                         hiddenElement.style.opacity += 1.0;
                    } 1000);


                }

                function despawnImage() {
                    document.getElementById('hiddenElement').style.display = 'none';
                    document.getElementById('bkgFade').style.visibility = 'hidden';
                }

Upvotes: -1

Views: 384

Answers (1)

jfriend00
jfriend00

Reputation: 707148

This piece of code makes no sense to me:

function spawnImage() {
     setInterval(function() {
        document.getElementById('hiddenElement').style.display = 'block';
        document.getElementById('bkgFade').style.visibility = 'visible';
        F hiddenElement.style.opacity += 1;
    });
    clearInterval();
}

There are multiple things wrong with it.

  1. You aren't setting a time for setInterval().
  2. You aren't saving the return value from setInterval().
  3. You aren't passing anything to clearInterval(). It should be passed the return value from setInterval(). It won't do anything the way you have it.
  4. This line isn't legal javascript: F hiddenElement.style.opacity += 1;
  5. I can't understand why you would setInterval() and then immediately clearInterval()
  6. Adding 1 to the opacity in a timer interval isn't going to accomplish anything. That's just going to make it visible in one giant step.
  7. Manipulating opacity directly won't work in some versions of IE.
  8. You're using document.getElementById('hiddenElement') in one place and hiddenElement in another place. If hiddenElement is valid, use that both places. If not, use document.getElementById('hiddenElement') both places.

If you describe in more detail what you're really trying to accomplish with this code, folks might be able to help you come up with correct code.

I would highly recommend that animation be done with a library like jQuery or YUI as it's way, way easier to use and make it work cross-browser.

Upvotes: 3

Related Questions