code works in jsfiddle but not in html document

I am a beginner with javascript and am hoping that someone can help me solve this issue. I am trying to make a div with the id, "move," slide back and forth. The code works in jsfiddle, but will not work when I place it into my html document. I have tried placing the top portion in a separate js file and calling the variable in the head only using the last line of the code:

animateMe($('#move'), 2000);

That did not work. I then tried placing the entire js script into the head and that also did not work. This is the code in the head of my html document:

<script type="text/javascript" src="javascript/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
 $(targetElement).css({ left: '50px', top: '50px' }).animate({
        'left': '200px'  },{
       duration: speed,
        complete: function () {
            $(this).animate({
            'left':'50px'
            },{
            duration: speed,
            complete: function () {
         animateMe(this, speed);
                }
            })
        }
        }
   ); 
  };
animateMe($('#move'), 2000);</script>

This is the code in the body. I normally use an external css document, but for the sake of trying to keep things shorter, I used inline css here.

<div id="move" style="position: absolute; width: 100px; height: 100px; background-color: green;"></div>

I am taking the code as is from jsfiddle and placing it into the head or into my separate js file though. Not sure if doing this is what is causing the script to not work. Any help is appreciated. Thank you all in advance.

This is the link to my work on jsfiddle: http://jsfiddle.net/wrdweaver6/r8Kf9/


You want to put your code inside either

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

or

window.onload = function() {
    // Your code here
};

All of the elements need to be loaded first before the javascript executes. With jsFiddle you don't have to do this, but this is probably what's causing it not to work outside of jsFiddle.


You need to add this around your code $(document).ready(function(){ }); so your code runs after the page has loaded.

Otherwise the code will be looking for html that doesn't exist yet.

$(document).ready(function(){
$(targetElement).css({ left: '50px', top: '50px' }).animate({
        'left': '200px'  },{
       duration: speed,
        complete: function () {
            $(this).animate({
            'left':'50px'
            },{
            duration: speed,
            complete: function () {
         animateMe(this, speed);
                }
            })
        }
        }
   ); 
  };
animateMe($('#move'), 2000);

});
链接地址: http://www.djcxy.com/p/72088.html

上一篇: 如何使用传单创建jsfiddle

下一篇: 代码在jsfiddle中工作,但不在html文档中