annaneedshelp annaneedshelp - 5 months ago 14
HTML Question

Javascript show div after a few clicks

I'm new in Javascript and I can't find the answer for my question. Is it possible that my javascript views a div after if you clicked on a button 5 times? If this is the case, how can I make this possible?

Thanks!

Answer

Without jQuery:

document.addEventListener("DOMContentLoaded", function(event) {
   var button = document.getElementById('click_me');
   var elem = document.getElementById('message');
   var count = 0;

   button.addEventListener('click', function(e) {
       e.preventDefault();
       count++;
  
       if(count == 5){
           elem.style.display = 'block';
       }
    }, false); 
});
#message {
  background: #0f0;
  display: none;
  padding: 10px;
}
<button type="button" id="click_me">Click Me</button>
<div id="message">Hello World</div>

With jQuery:

$(function() {
  var count = 0;
  
  $('#click_me').click(function(e) {
    e.preventDefault();
    count++;
    
    if(count == 5) {
      $('#message').show();
    }
  });
});
#message {
  background: #0f0;
  display: none;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" id="click_me">Click Me</button>
<div id="message">Hello World</div>