Bart. K Bart. K - 5 months ago 10
Javascript Question

Set timer for specific elements

I have a grid with 25 clickable items. If someone clicks on a desired item, a timer for this item should start. After the timer reaches 0, the item should get hidden. What is the best way to do this?

This is the grid:

<ul class="field">
<?php
for($i = 1; $i<26; $i++){
?>
<li id="item-<?php echo $i; ?>" data-specie="test-<?php echo $i; ?>" data-level="0" class="field-item">
<img>
<!--</li>-->
<?php
}
?>
</ul>


And this is the jquery part:

$(".field-item").click(function()
{
var level = $(this).data('level');
level ++;
$(this).data('level',level);
$(this).find( "img" ).attr("src","../css/images/plant-1-"+level+".png");

setTimeout(progress, 3000);
});


And this is the function that should only hide the grid-item that has been clicked on. (I know this won't work by the way, I just don't know how to do this part.)

function progress(){
$(this).hide();
}

Answer

should only hide the grid-item that has been clicked on

You could pass the current instance of clicked element using bind() as mentioned in @Andreas comment, so it will be :

setTimeout(progress.bind(this), 3000);

Instead of :

setTimeout(progress, 3000);

Hope this helps.

Comments