m33bo
m33bo

Reputation: 1354

Basic Javascript click function not loading

I am just trying to change the font attribute via a click function real beginner stuff, however I want to check if the element has been clicked a second time and do something if so.

var clicks = 0;
document.getElementById('button2').click(function(){
  clicks++;
  if(clicks%2===0){
    document.getElementById('demo2').style.fontSize='22px';
  } else{
    document.getElementById('demo2').style.fontSize='12px';
  }
});

What am i doing wrong?

Upvotes: 0

Views: 39

Answers (2)

Joe Warner
Joe Warner

Reputation: 3452

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/onclick

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

.click fires a click, it doesn't watch for them

var clicks = 0;
document.getElementById('button2').onclick = function(){
  clicks++;
  console.log(clicks)
  if(clicks%2===0){
    document.getElementById('demo2').style.fontSize='22px';
  } else{
    document.getElementById('demo2').style.fontSize='12px';
  }
};
<div id="button2">button2</div>

<div id="demo2">demo2</div>

This is what you should do though just toggle a class look how much code is removed and it does the exact same thing :)

const button = document.querySelector('.button2');
const demo = document.querySelector('.demo2');

button.addEventListener('click', () => demo.classList.toggle('large'));
.demo2 {
  font-size: 12px;
}

.large {
  font-size: 22px;
}
<div class="button2">button2</div>

<div class="demo2">demo2</div>

Upvotes: 0

sjahan
sjahan

Reputation: 5960

Why not using an event listener instead?

According to the mozilla documentation (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click), the click function does not expect a function that defines the behavior of the click.

Try the following:

var clicks = 0;
document.getElementById('button2').addEventListener('click', function(){
  clicks++;
  if(clicks%2===0){
    document.getElementById('demo2').style.fontSize='22px';
  } else{
    document.getElementById('demo2').style.fontSize='12px';
  }
});
<button id="button2">Click me</button>
<div id="demo2">Hello</div>

Upvotes: 3

Related Questions