Posts

Showing posts with the label Onclick

AddEventListener Vs Onclick

Answer : Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches. Event Listeners (addEventListener and IE's attachEvent) Earlier versions of Internet Explorer implement javascript differently from pretty much every other browser. With versions less than 9, you use the attachEvent [doc] method, like this: element.attachEvent('onclick', function() { /* do stuff here*/ }); In most other browsers (including IE 9 and above), you use addEventListener [doc], like this: element.addEventListener('click', function() { /* do stuff here*/ }, false); Using this approach (DOM Level 2 events), you can attach a theoretically unlimited number of events to any single element. The only practical limitation is client-side memory and other performance concerns, which are different for each browser. The examples above represent using an anonymous function[doc]. You can also add an event liste...

Change Button Color OnClick

Answer : There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation. Your code could look like this: <script> var count = 1; function setColor(btn, color) { var property = document.getElementById(btn); if (count == 0) { property.style.backgroundColor = "#FFFFFF" count = 1; } else { property.style.backgroundColor = "#7FFF00" count = 0; } } </script> Hope this helps. 1. function setColor(e) { var target = e.target, count = +target.dataset.count; target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF'; target.dataset.count = count === 1 ? 0 : 1; /* () : ? - this is conditional (ternary) operator - equals if (count === 1) { target.style.backgroundColor = "#7FFF00"; target.dataset.count = 0; } else { ...