Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make these functions into one function?

Tags:

javascript

I'm trying to get this program to add a special character when the assigned button for the character is pressed. The problem is, I'm going to have a lot of functions. Can I somehow just make one function that I can use for all of the buttons?

//These are buttons
var aa = document.querySelector('#aa')
var oo = document.querySelector('#oo')
var uu = document.querySelector('#uu')
var khii = document.querySelector('#khii')
//This is the text box
var textBox = document.querySelector('#typeIn')


//Functions to add a character into the text box
function addAa() {
   textBox.innerHTML += "ā";
}

function addOo() {
    textBox.innerHTML += "ō";
}

function addUu() {
    textBox.innerHTML += "ū";
}

function addKhii() {
    textBox.innerHTML += "χ";
}

//Telling the buttons to call on the functions when clicked
aa.onclick = addAa
oo.onclick = addOo 
uu.onclick = addUu
khii.onclick = addKhii

Additionally: why does this not work?

var aa = document.querySelector('#aa')
var textBox = document.querySelector('#text')

function addLetter(a) {
  textBox.innerHTML += a
}

aa.onclick = addLetter("ā")

This just adds the character once into the text box. Clicking on the button then does nothing. Why does it do that?

like image 786
0deboy Avatar asked Sep 16 '25 13:09

0deboy


1 Answers

Yes you can do it with only one function. Pass the character as parameter to the function. Like that:

version with addEventListener (prefered)

const btns = document.querySelectorAll('button');
const textBox = document.querySelector('#typeIn');

btns.forEach(b => {
  b.addEventListener('click', e => {
    textBox.innerHTML += e.target.getAttribute('data-char')
  })
});
#typeIn {
  margin:10px;
  padding: 10px;
  color: white;
  min-height:40px;
  background: gray;
}
<button data-char="aa">aa</button>
<button data-char="X">X</button>
<button data-char="ō">ō</button>
<button data-char="ū">ū</button>
<div id="typeIn"></div>

Generally try to avoid onclick events and use eventListener instead.

Version onclick Event

const textBox = document.querySelector('#typeIn');

function add(what) {
   textBox.innerHTML += what;
}
#typeIn {
  margin:10px;
  padding: 10px;
  color: white;
  min-height:40px;
  background: gray;
}
<button onclick="add('aa')">aa</button>
<button onclick="add('X')">X</button>
<button onclick="add('ō')">ō</button>
<button onclick="add('ū')">ū</button>
<div id="typeIn"></div>
like image 105
Maik Lowrey Avatar answered Sep 18 '25 09:09

Maik Lowrey