1
$("ul").on("click", ".start", function() {
    console.log("started");
    var timeInput = $(this).parent().children('.time');
    var timeInputValue = timeInput.val();
    var milliSeconds = Number(timeInputValue)*60*1000;
    console.log(milliSeconds);
    setTimeout(function(){
        alert("Time Over");
        $(this).parent().children('.task').toggleClass("completed");
    }
        , milliSeconds);
})

....................................................................

<ul>
        <li><span class="delete">X</span> <span class="start">S</span> <span class="task">Code ToDo</span></li>
        <li><span class="delete">X</span> <span class="start">S</span> <span class="task">Read two books</span></li>
        <li><span class="delete">X</span> <span class="start">S</span> <span class="task">Run</span></li>       
    </ul>

I know I am using the this keyword wrong inside the setTimeout function, but I want to access,the element with class .task respective to the start.

How do I do that?

The alert method is working, but the toggleClass is not working.

relentless-coder
  • 1,248
  • 1
  • 15
  • 34

1 Answers1

2

You could use arrow function to do that,

setTimeout(() => {
   alert("Time Over");
   $(this).parent().children('.task').toggleClass("completed");
 }, milliSeconds);

If you are writing your code in ES5 then use the 3rd parameter of setTimeout,

 setTimeout(function(_this){
   alert("Time Over");
   $(_this).parent().children('.task').toggleClass("completed");
 }, milliSeconds, this);
Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119
  • 1
    Hey, thank you. Although, the arrow function is a little bit harder for me to understand, but for some reason makes more sense than what I found on the internet. – relentless-coder Nov 10 '16 at 13:51