0

I created some functions in js, something very simple, and instead of calling these functions directly in the html I decided to execute them looking for the input id.

It was like this:

...
functions here
...

function id(el){
    return document.getElementById(el);
}
    window.onload = function(){
    id('name').onkeyup = function(){inicialMaiuscula(this);}
    id('phone').onkeyup = function(){mascara(this, mtel);}
    id('postalcode').onkeyup = function(){mascara(this, cepm);}
}

The problem is that this js file is loaded on different pages, so if the input with that id doesn't exist it returns the error:

can't access property "onkeyup", id(...) is null

And also on some pages the function works and on others it doesn't. Tips on how I can get around this?

I take the opportunity to ask another question, there are inputs that use the same function. How can I declare both id on the same line without having to repeat all the code?

Clebson
  • 296
  • 1
  • 12
  • As the error is saying, you first need to check if the `id()` call is returning a real Element or is returning `null`. One common way is to save the result of the call into a variable, check if that variable is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), and only set the `onkeyup` property if it is. `const name = id('name'); if (name) { name.onkeyup = ... }`. Additionally, I would recommend to use [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) rather than the special `onkeyup` property. – romellem Aug 01 '22 at 20:47
  • Why add it to every page when it does not exist? Just causing the page to take longer to load to check to see if an element exists. But the answer is as simple as `id('name')?.onkeyup = function(){inicialMaiuscula(this);}` but the real answer is don't include it. – epascarello Aug 01 '22 at 20:53
  • @epascarello This file really needs to be loaded on every page. Nice tip, very interesting and simple. – Clebson Aug 01 '22 at 20:59
  • @romellem Thus? `id('nome')?.addEventListener("keyup", function(){ inicialMaiuscula(this); });` – Clebson Aug 01 '22 at 20:59
  • @epascarello you can't do an assignment with [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). @Clebson, yes `id(...)?.addEventListener(...)` would work since `addEventListener` would only be called if the previous `id(...)` return was non nullish. – romellem Aug 01 '22 at 21:04
  • @romellem Hm.. Ok, do you know if I can pass two id's to use the same function without having to repeat the line? – Clebson Aug 01 '22 at 21:09
  • Nice tip, yes it is. Modules make lives better. Simple includes. Not knowing the whole picture we can not give exact tips, just generic ones. – epascarello Aug 01 '22 at 21:46
  • ...That completely negates the point of your helper. Maybe you are looking for something like [querySelectorAll](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll), and you can call it with `'#name, #phone, #postalcode'`. You'd need to loop over its returned NodeList to attach each event separately. If you find stuff like this tedious, (as old as it may be) maybe a library like [jQuery](https://jquery.com/) could be useful? If you are interacting with the DOM imperatively, jQuery smooths out some of the rough edges of the DOM APIs. – romellem Aug 01 '22 at 21:47
  • 1
    What is up with not wanting to repeat code? What exactly are you trying to avoid? I seem to be missing the second point of this question. – epascarello Aug 01 '22 at 21:47
  • @epascarello I just wanted to simplify the code, so it doesn't get too long. – Clebson Aug 01 '22 at 21:48
  • What is there to simplify? I am not seeing exactly code that repeats here. – epascarello Aug 01 '22 at 21:50
  • 1
    Don't worry about that this early. Focus on getting everything working because you look to refactor / "simplify the code." – romellem Aug 01 '22 at 21:50
  • 1
    https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil – epascarello Aug 01 '22 at 21:51
  • You are right, thank you so much for all the support. I'll focus on how it works from now on. At first everything is working fine with the tips provided so far. – Clebson Aug 01 '22 at 21:54

0 Answers0