javascriptaddeventlisteneronmouseover

How te display delete button from a TODO list


I am making a todo list and i have a function that display (it adds opacity) the delete button when i have the mouse over the correspondant Li.

  todosUl.addEventListener("mouseover", function(event) {
  var elementHovered = event.target;
  var deleteButton = document.getElementById("deleteButton"+elementHovered.id)
  deleteButton.style.opacity=1;
  });
  todosUl.addEventListener("mouseout", function(event) {
  var elementHovered = event.target;
  var deleteButton = document.getElementById("deleteButton"+elementHovered.id)
  deleteButton.style.opacity = 0;
  });

the problem is that whenever I approach the area of the button, the button dissapears again. when this happens, the console shows this: Cannot read property 'style' of null

this is how i created the Li :

todoLi.appendChild(view.createDeleteButton(position));

createDeleteButton: function (liId) {
    var deleteButton = document.createElement('button');
    deleteButton.textContent = 'X';
    deleteButton.className = 'deleteButton';
    deleteButton.id = 'deleteButton'+liId;
    return deleteButton;

Solution

  • Any particular reason you need the js for this rendering? Below is an html/css model

    .delete {
      opacity: 0;
    }
    li:hover > .delete {
      opacity: 1;
    }
    <ul id="toDos">
      <li>To Do Item 1<input type="button" class="delete" value="Delete"/></li>
      <li>To Do Item 2<input type="button" class="delete" value="Delete"/></li>
      <li>To Do Item 3<input type="button" class="delete" value="Delete"/></li>
      <li>To Do Item 4<input type="button" class="delete" value="Delete"/></li>
    </ul>