0

I'm trying to create a simple counter website using HTML, CSS and JS (Hypertext Markup Language, Cascading Stylesheets and JavaScript). I use this HTML code: jswebsite.html

<!DOCTYPE html>
<html>
    <head>
        <title>JS Website</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="styles3.css">
        <link rel="script" href="script1.js">
    </head>
    <body>
        <h1>Counter</h1>
        <p id="counter"></p>
    </body>
</html>

This CSS code: styles3.css

body {
    background-color: rgb(255, 169, 0);
}

h1, p {
    text-align: center;
    color: rgb(255, 69, 0);
    background-color: rgb(148, 43, 226);
    margin-left: auto;
    margin-right: auto;
}

And this JS code: script1.js

var number = 0;
var i = 0;

while (i < 1) {
    document.getElementById("counter").innerHTML = number;
    number++;
}

Instead of giving me a counter, it just shows the heading and give me no other text.

Am I doing anything wrong?

Nothing to see on the expansion.

0

1 Answer 1

0

The issue is how you linked to the script in your HTML. You should use the <script> tag, not <link>, like this:

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

I'd also recommend a change to your JavaScript, since your current code will probably freeze the page. If you want the number to move up once per second, for example, your current JS won't work; it will just move the number up forever without any delay and probably crash.

var number = 1; // Start with one, since setInterval won't run the code initially but waits until the first second has passed

// Update the counter every second (1000 ms)
setInterval(function() {
    document.getElementById("counter").innerHTML = number;
    number++;
}, 1000);
body {
    background-color: rgb(255, 169, 0);
}

h1, p {
    text-align: center;
    color: rgb(255, 69, 0);
    background-color: rgb(148, 43, 226);
    margin-left: auto;
    margin-right: auto;
}
<!DOCTYPE html>
<html>
    <head>
        <title>JS Website</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="styles3.css">
        <!-- Correct way to link the JavaScript file -->
        <script src="script1.js"></script>
    </head>
    <body>
        <h1>Counter</h1>
        <p id="counter">0</p>
    </body>
</html>

You could keep your original counter implementation, but I don't recommend it. Also, you might want to add defer to your script to make sure that the HTML page is fully loaded before running it, or you'll get errors from JS when you try to select the counter element…

<script src="script1.js" defer></script>
Sign up to request clarification or add additional context in comments.

1 Comment

@LeviB414 I uploaded the solution to GitHub. You can download the files and test it easily here: github.com/The-Best-Codes/stackoverflow-solutions/tree/main/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.