Constantly Updating Variables in a HTML Page

As part of a HTML and Flask project i’m working on, i’m trying to make it so if you click a button, a point is added to a counter, the problem is I don’t know how to make it so the new variable is constantly showing and updating on the HTML page without the user having to manually refresh, is there a simple way to achieve this?

Use JavaScript, the template variables cannot be changed.

<span id="counter">{{ num }}</span>
<script>
  let counter = document.getElementById("counter");
  addEventListener("click", () => {
    counter.innerText = parseInt(counter.innerText) + 1;
  });
</script>

How would I implement this into Flask and HTML?

“main.py” (backend):

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
  return render_template("index.html", num=0)

app.run('0.0.0.0', port=81)

“templates/index.html” (frontend)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Counter</title>
  </head>
  <body>
    <span id="counter">{{ num }}</span>
    <script>
      let counter = document.getElementById("counter");
      counter.addEventListener("click", () => {
        counter.innerText = parseInt(counter.innerText) + 1;
      });
    </script>
  </body>
</html>
2 Likes

Thanks for the help!

You’re welcome! Thanks for marking me as solution

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.