Search code examples
javascriptgoogle-chromedreamweavercompatibilitysetinterval

javascript setInterval() working in Dreamweaver but not in Chrome


I'm trying to make an image drop up/down from a menu whenever the user clicks on the menu image which hasonClick="move()"in the tag. So far The image starts at the top of the page, behind the menu, so it is hidden, then slides down as intended. However, after the image reaches it's stopping point, clicking the menu again does nothing at all when I test the page in both IE and Chrome. In Dreamweaver, the code executes as intended, with the ability to slide the image up after it reaches the bottom and back down again. I've tried changing the call to setInterval() because I assumed that is where the problem was but nothing seems to be working. Why does Dreamweaver execute the code properly but not Chrome or IE?

    var onMusic=false;
    var id;
    function move() {
        if(!onMusic) {
          moveDown()        
        }
        else {
            moveUp()
        }
    }


    function moveUp() {
        top=100
        id = setInterval(function() {
            top-=10  // update parameters 
            document.getElementById('guitar').style.top = top + 'px' // show frame
            if (top <= -500)  {// check finish condition
                onMusic=false
                clearInterval(id)
            }
         }, 10) // draw every 10ms
    }

    function moveDown() {
        var top=-500
        id = setInterval(function() {
            top+=10  // update parameters 
            document.getElementById('guitar').style.top = top + 'px' // show frame
            if (top == 100)  {// check finish condition
                onMusic=true
                clearInterval(id)
            }
        }, 10) // draw every 10ms
    }

Solution

  • I think the problem was:

    top=100
    // should be
    var top = 100;
    

    You can try in the console to see what I mean:

    >top = 12 
    12 
    > top 
    Window {top: Window, window: Window, location: Location, Proxy: Object, external: Object…}
    

    But I cleaned it up a little more in jsfiddle: http://jsfiddle.net/pNh57/1/