1

I am very new to javascript and just started 2-3 months ago. Please forgive me if the answer is obvious. I would like to create a memorial section for my chihuahua blog, where people can light a candle for their lost pup. I'd like it to show how many candles have been lit, all time. I have come up with this:

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Light a Candle</button>

<p id="candle"></p>

<script>
const candleLit = " Candles lit"
var count = 0;
function myFunction() {

document.getElementById("candle").innerHTML = ++count + candleLit
}
</script>

</body>
</html>

It does work, but when I refresh the page the count is gone. I assume I need some kind of database to do this? I have access to a database on my website, but don't know how to work with it or connect it. Can someone help me figure out what I need to progress with this?

Thank you for your valuable time.

1 Answer 1

0

There are multiple ways to accomplish this. With the database, depending on what database you're using, the code will be slightly different, but there's good documentation available online if you search up "[database tool] adding and retrieving records" to get started. I would suggest learning how to fetch data because it's a useful skill as you progress with web development, but it may not be the most efficient way for storing the click count.

Another method is writing the candle click count to a file and adding an event handler to increment/update the count data whenever the user clicks the candle. That way, whenever the user refreshes the page, you fetch the new, updated click count from the file. However, this can not be done with pure JS. You need to install node.js, a framework that will allow you more flexibility in what you can do.

const fs = require('fs'); //fs stands for file system

fs.readFile('clickCounter.txt', 'utf-8', (err, data) => {
  if(err) {
    console.error(err);
    return;
  }
  fs.writeFile('clickCounter.txt', (data+=1), err => {
    if(err) {
      console.err;
      return;
    }
  });

  //update element displaying counter here

});

//code inspired by this video -> https://www.youtube.com/watch?v=zMX3gqs3Y7I
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this is amazing! You've opened up a whole new world for me to expand my javascript knowledge. I really appreciate your time to break this down for me so I can try different methods for my script. Thank you so much!
No worries, I'm glad I could help!

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.