Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
When ever I try onclick function, I get reference error

I am trying to use the on-click event in my javascript file. But, whenever, I use it, it says that the function is declared, but never used. Can you please help me resolve this issue? You can check the code below, as well as in the image.

let showtoDos = () => {
  let li = "";
  if(toDos) {
  toDos.forEach((todo, id) => {
    li += `<li class="task">
        <label for="${id}">
          <input class="clicked" type="checkbox" id="${id}" />
          <p>${todo.name}</p>
        </label>
        <div class="settings">
          <i id="ellipsis" class="fa-solid fa-ellipsis"></i>
          <ul class="task-menu">
            <li><i class="fa-solid fa-pen"></i>Edit</li>
            <li onclick="deleteTask(${id})" class="delete" ><i class="fa-solid fa-trash"></i>Delete</li>
          </ul>
        </div>
      </li>`;
  });
}
  taskBox.innerHTML = li;
}
showtoDos();

function deleteTask(deletedId) {
  console.log(deletedId);
}

picture of the code in vscode

Moreover, you can check in the below image that, whenever I click on the delete button on the browser, it gives a reference error.

code in the browser

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

You have two different problems there:

  1. The IDE is doing validation of your code showing warnings and can't find any line calling that function. The only point you targeted that function is when you defined the onclick attribute of the li element but it happened inside a string literal and it doesn't count for the linter. You can ignore this.
  2. The javascript code you have in that file won't run in the global scope so the function defined there won't be visible to the li item when its event will fire. You should try attaching an event handler via javascript so to be sure the handler will be attached until you still have control of that scope.

Just after you showToDos() you can try to run the following:

//for each delete list item
document.querySelectorAll('li.task ul.task_menu li.delete')
  .forEach( (o, i) => {
    //bind an handler (deleteTask) for its click event (deleteTask should be in this scope now)
    o.addEventListener("click", deleteTask);
  });

DISCLAIMER:

Unfortunately that selector I used with querySelectorAll will get ALL those items even those that already got the handler attached (if any already existed with the same selector criteria). Before doing addEventListener, one strategy could be to check if there's already an handler for that event on that object.

A better solution would be to use that html code you crafted with a template string, create an html elements tree from there and call querySelectorAll(+attachEventHandler) from such object before appending it to taskbox. It wouldn't require you to make any check before attaching the event handler because you'll be targeting only the newly created ones.

Or you could as someone suggested to make that function available in the global scope but it wouldn't scale really well due to name collisions (this is one of the unsafe ways to do it):

var deleteTask = (/*args*/) => {/*code here*/}
about 4 years ago · Santiago Gelvez Denunciar

0

You need to place your function in the global scope (window object in browser) if you want to access it like that, try:

  window.deleteTask = function (deletedId) {
  console.log(deletedId);
}
about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda