user3683991 user3683991 - 1 year ago 37
jQuery Question

How to make this Javascript function work for more elements

I have this 'building' feature I've been working on and I ran into a problem. When you push a certain button, a timer will be shown to the user. This actually works just fine. However, when another button of the same category is pushed, the timer will only show up for the first one
as you can see at this picture

All those buildings are being looped from the database.
Within this loop is the Javascript function that shows the timer. (Using Jquery countdown).

Is there anyone who could show me how to make this countdown timer loop correctly as well?

This is the timer part within the PHP loop:

<button class="btn btn-disabled" type="button">Workers are currently working on this property</button>
<span>Time untill completion: <span id="cd" data-countdown-id="<?php echo $userrow['building_id']; ?>" data-countdown="<?php echo $timedifference->format("%H:%I:%S"); ?>"></span> </span>

$(function createCountDown() {
var cd = document.getElementById("cd")
var countdown = cd.getAttribute("data-countdown")
var cdid = cd.getAttribute("data-countdown-id");
$('#buycd' + cdid).countdown({
until: countdown

<div id="buycd<?php echo $userrow['building_id']; ?>"></div>

If you need to see more of the code, please tell me.

PS: If I only start one timer, it works fine on any of them.


You are using cd as the id, but from your comment, that is being applied to multiple elements. Elements must have unique ids (or no id). So you should use a class for this e.g. class="cd".

then you code looks like:

$(function createCountDown() {
        var countdown = $(this).attr('data-countdown');
        var cdid = $(this).attr('data-countdown-id');
        $('#buycd' + cdid).countdown({
          until: countdown

I didn't test that snippet... expect bugs :)