简体   繁体   中英

How do you insert javascript code into HTML

I have learned to build a fun piece of javascript on codeacademy and wanted to add it on a html document. How would I go about doing this or is it even possible?

Here is the site. I tried to use script tags but they do not work. Not sure if I am putting them in the right place.

http://www.codecademy.com/courses/animate-your-name/0/2

Looking at the Codeacademy link, it seems as if there are some dependancies. You need to make sure to include those. Your HTML file should look like this. Note: You should probably combine all of your JS into an external file and link it with <script src="main.js"></script> tags. Also, make sure that your script tags come at the end of the page (but before the </body> ), it will make your page faster as your JS won't block the DOM construction.

Update

If you included all of the known dependancies and it still doesn't seem to work, Codecademy probably buried some important code somewhere. The easiest way to get around this would be to just download the web page itself as an HTML file (option click on the link on mac) and either use that or poke around to make sure you have everything.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
var myName = "Codecademy";

var red = [0, 100, 63];
var orange = [40, 100, 60];
var green = [75, 100, 40];
var blue = [196, 77, 55];
var purple = [280, 50, 60];
var letterColors = [red, orange, green, blue, purple];

drawName(myName, letterColors);

if(10 < 3)
{
    bubbleShape = 'square';
}
else
{
    bubbleShape = 'circle';
}

bounceBubbles();
</script>
<script type="text/javascript" src="http://s3.amazonaws.com/codecademy-content/courses/hour-of-code/js/bubbles.js"></script>
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://s3.amazonaws.com/codecademy-content/courses/hour-of-code/js/alphabet.js"></script>
</body>
</html>

You can add inline JavaScript by using the <script> tag.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

EDIT

Sorry I didn't notice that you've already tried the script tags. Can you post your HTML with the script tags?

The best way is to use the <script> tags. So if you want to embed some javascript into html, you can use someone elses (or your own) like this: <script src="www.blah.blah/blah/blah.js"></script> or write the js on your computer like this:

<script src="helloWorld.js"></script>

Another way is to write the JavaScript into the file it's self. Write Js into HTML like this:

<script>
//Your Js Goes Here
</script>

Hope this is what you needed!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM