-1

i have a card that is created every time a button is pressed, one of the parts of the card is the remove icon. I want to remove the card when the remove button is clicked. i am using this code:

let icon = document.createElement('span');
    icon.className = "span_x";
    document.getElementsByClassName('close')[0].appendChild(icon);
    document.getElementsByClassName('span_x')[0].innerHTML = '<i class="fa fa-remove"></i>';
    icon.addEventListener('click', removeTask());

i tried the last line of code in a few ways, like:

icon.onclick = function()
icon.setAttribute("onclick","removeTask()");

but whatever i'm trying, it always runs the function when creating the card (task), even though i didn't clicked on the icon. i hope i'm being clear enough. thank you for your help.

Yuda
  • 69
  • 7

2 Answers2

2

Try this:


xBtn.addEventListener('click', removeTask);

Tech Helper
  • 51
  • 1
  • 4
1

You need to remove the brackets. You're invoking the function right away, when you just need to pass a reference to it

icon.setAttribute("onclick", removeTask)

const removeTask = () => {
  console.log('clicked')
}

let icon = document.createElement('span');
icon.className = "span_x";
document.getElementsByClassName('close')[0].appendChild(icon);
document.getElementsByClassName('span_x')[0].innerHTML = '<i class="fa fa-remove"></i>';
icon.addEventListener('click', removeTask);
.close {
  width: 100px;
  height: 100px;
  background: green;
}

.span_x:after {
  content: 'Click'
}
<div class="close"></div>
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81