I’m building a virtual keyboard with vanillla javascript but don’t know where to add the onclick event listener to the buttons or how to grab them. I have a printKeys function that loops thru the array and prints them onload, and I have an unfinished typeKeys function where I’m trying to grab the innerhtml and print it to the input field.
HTML
</head> <body onload="printKeys()"> <div class="text"> <input type="text" class="your-text" id="input" placeholder="Your text here.."></input> <button class="copy-btn">Copy</button> </div> <div class="keyboard" id="keyboard"></div> <script src="index.js"></script> </body> </html>
Javascript
const alphaKeys = ["a","b","c"]; const numKeys = "1234567890"; const keyboard = document.getElementById("keyboard"); // render keyboard function printKeys() { for (let i = 0; i < alphaKeys.length; i++) { let keys = document.createElement("button"); keys.innerHTML = alphaKeys[i]; //add onclick function to button keyboard.appendChild(keys); } } //onClick event, add text in text field const input = document.getElementById('input') function typeKeys() { console.log("clicked") //grab input and replace with button innerhtml }
Advertisement
Answer
Instead of adding the event handler to each button, you can apply it to the parent (keyboard) then just use the event’s target to get the specific button. I also added the character to a data-attribute instead of the innerHTML.
const alphaKeys = ["a","b","c"]; const numKeys = "1234567890"; const keyboard = document.querySelector(".keyboard"); // render keyboard function printKeys() { for (let i = 0; i < alphaKeys.length; i++) { let keys = document.createElement("button"); keys.innerHTML = alphaKeys[i]; keys.setAttribute("data-character",alphaKeys[i]); keyboard.appendChild(keys); } } //onClick event, add text in text field const input = document.getElementById('input') function typeKeys(character) { input.value += character; } keyboard.addEventListener("click",function(e){ let target = e.target; if(target.getAttribute("data-character")){ typeKeys(target.getAttribute("data-character")) } }); printKeys();
<div class="text"> <input type="text" class="your-text" id="input" placeholder="Your text here.."> <button class="copy-btn">Copy</button> </div> <div class="keyboard" id="keyboard"></div>