JavaScript variable does not retain value across mouseDown() events

I'm a bit of a beginner, I started JavaScript around a week ago. I can't figure out what's wrong with my code.

my guess is it has something to do with the id and html but I could be wrong.

HTML:

<!-- imports font -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<!--Gets css and java files-->
<script src="js/Untitled2.js"></script>



<title>just click</title>

<html>
    <button onclick="mouseDown()">press</button>
    <p id='count'>0</p>
</html>

JavaScript:

function mouseDown() {
    clickCount = clickCount + 1;
    document.getElementById('count').innerHTML = clickCount;   
}

Thanks for the advice.

Upvotes: 0

Views: 53

Answers (3)

Hyunwoong Kang
Hyunwoong Kang

Reputation: 530

Maybe you should make clickCount persist.

let clickCount = 0;
const mouseDown = () => {
  clickCount += 1;
  document.getElementById('count').innerHTML = clickCount;
}

Upvotes: 1

user14420666
user14420666

Reputation:

1:

clickCount = clickCount + 1; you can use clickCount++

2: clickCount was not defined

3: Check Arthur Pereira's answer it's good ( or Hyunwoong Kang )

4: how was that a week??? and "java" files you mean javascript?

Upvotes: 0

Arthur Pereira
Arthur Pereira

Reputation: 1559

That is because you are referencing clickCount before initializating it. One solution would be to declare it global starting with zero. Or getting the value every time you click, like this:

function mouseDown() { 
  count = document.getElementById('count').innerHTML
  clickCount = Number(count) + 1; 
  document.getElementById('count').innerHTML = clickCount;    

Upvotes: 1

Related Questions