<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Recording</title> <link rel="stylesheet" href="main.css"> </head> <body> <section class="calculator"> <form> <input type="text" name="" id="" class="screen"> </form> <div class="buttons"> <!-- yellow --> <button type="button" class="btn btn-yellow" data-num="*">*</button> <button type="button" class="btn btn-yellow" data-num="/">/</button> <button type="button" class="btn btn-yellow" data-num="-">-</button> <button type="button" class="btn btn-yellow" data-num="+">+</button> <!-- grey buttons --> <button type="button" class="btn btn-grey" data-num=".">.</button> <button type="button" class="btn btn-grey" data-num="9">9</button> <button type="button" class="btn btn-grey" data-num="8">8</button> <button type="button" class="btn btn-grey" data-num="7">7</button> <button type="button" class="btn btn-grey" data-num="6">6</button> <button type="button" class="btn btn-grey" data-num="5">5</button> <button type="button" class="btn btn-grey" data-num="4">4</button> <button type="button" class="btn btn-grey" data-num="3">3</button> <button type="button" class="btn btn-grey" data-num="2">2</button> <button type="button" class="btn btn-grey" data-num="1">1</button> <button type="button" class="btn btn-grey" data-num="0">0</button> <button type="button" class="btn-equal btn-grey">=</button> <button type="button" class="btn-clear btn-grey">C</button> </div> </section> <script> //Wrap code in an IIFE (function(){ let screen = document.querySelector('.screen'); let buttons = document.querySelectorAll('.btn'); let clear = document.querySelector('.btn-clear'); let equal = document.querySelector('.btn-equal'); //retrieve data from numbers that are clicked buttons.forEach(function(button){ button.addEventListener('click', function(e){ let value = e.target.dataset.num; screen.value += value; }) }); equal.addEventListener('click', function(e){ if(screen.value === ''){ screen.value = 'Please Enter a Value'; } else { let answer = eval(screen.value); screen.value = answer; } }) clear.addEventListener('click', function(e){ screen.value = ''; }) })(); //end IIFE </script> </body> </html>
e.target
.dataset
data-*
.num
data-num
Quote: Attributes can be set and read by the camelCase name/key as an object property of the dataset: element.dataset.keyname
element.dataset.keyname
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)