Home » Javascript » Timers in .addEventListener doesnt work?

Timers in .addEventListener doesnt work?

Posted by: admin October 29, 2018 Leave a comment

Questions:

I’m trying to convert a small piece of jQuery to vanilla JS, and I cannot seem to get timers to work within an .addEventListener.

I’m not sure if they can even work like this.

I’ve uploaded my work to Plunkr the greyed out code in the JS is the Vanilla JS.

https://embed.plnkr.co/up5i33T4LfTmpXhy86wM/

Everything works apart from the delay, it skips the delay as if its not there.

Here is the jQuery version which works great:

//jQuery VERSION
$("span").click(function (e) {
    $(this).parent().fadeOut(500, function(){
        $(this).remove();
    });
    e.stopPropagation();
});

And here is my vanilla attempt:

//JavaScript Version - DOESNT WORK!!!
var spans = document.querySelectorAll("span");

for (var i = 0; i < spans.length; i++) {
    spans[i].addEventListener("click", function () {
        this.parentElement.classList.add("fadeOut");
        setInterval(test(this), 2000);

    });
}

function test(event){
    console.log(event);
    event.parentElement.outerHTML = "";
};

The CSS for the Vanilla is:

/* STYLES FOR JS */
.fadeOut{
    opacity: 0;
    transition: all 0.6s;
    -webkit-transition: all 0.6s;
}

and the HTML being manipulated is very simple:

<div id="container">
       <h1>TO-DO LIST</h1>
       <input type="text">
       <ul>
           <li><span>X</span> Go to Potions Class</li>
           <li><span>X</span> Buy New Robes</li>
           <li><span>X</span> Visit Hagrid</li>
       </ul>

   </div>
Answers: