1

I'm new to javascript and I wrote a simple code to change some words inside an h1 tag. Here are my HTML and JavaScript files:

var element;
var words = ["Cute","Nice","Playful"];
var current = 0;
function increment () {
	current++;
	if (current === words.length) {
		current = 0;
	}
	setTimeout('changeWord()', 1000);
}

function changeWord () {
	element.innerHTML = words[current];
	setTimeout('increment()', 2000);
}
<!DOCTYPE html>
<html>
<head>
	<title>test</title>
	<script type="text/javascript" href="script.js"></script>
</head>
<body>
<h1>This dog is <span id="atribute"></span></h1>
<script type="text/javascript" href="script.js">
	element = document.getElementById("atribute");
	changeWord();
</script>
</body>
</html>

The problem is that this thing doesn't work. If I move the JS into a script tag inside the HTML document, it does work. So, how can I use that external JS document?

0

1 Answer 1

2

When you specify a script file then you have to use 'src' as the source attribute. Besides in your 2nd script below the html you dont need to specify the source because it is considered as internal script. So remove it's source attribute. And your fresh code will be:

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>This dog is <span id="atribute"></span></h1>
<script type="text/javascript">
    element = document.getElementById("atribute");
    changeWord();
</script>
</body>
</html>  

JavaScript:

var element;
var words = ["Cute","Nice","Playful"];
var current = 0;
function increment () {
    current++;
    if (current === words.length) {
        current = 0;
    }
    setTimeout('changeWord()', 1000);
}

function changeWord () {
    element.innerHTML = words[current];
    setTimeout('increment()', 2000);
}// JavaScript Document
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.