Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
jQuery/Javascript data attribute value undefined on callback

I have these below function for countdown.

$.fn.countdown = function(toTime, callback){
  let $el = $(this);
  var intervalId;

  intervalId = setInterval(function() {
    var now = new Date().getTime();
    var distance = toTime - now;

    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    if(distance < 0){
      clearInterval(intervalId);

      if (typeof callback == 'function'){
        callback.call(this);
      }
    }
    else{
      var value = days + "<sup>d</sup> " + (hours > 9 ? hours : '0' + hours) + ":" +  (minutes > 9 ? minutes : '0' + minutes) + ":" +  (seconds > 9 ? seconds : '0' + seconds);
      $el.html(value);
    }
  }, 1000);
};

var date1 = new Date();
date1.setSeconds(date1.getSeconds() + 5);

var date2 = new Date();
date2.setSeconds(date2.getSeconds() + 7);

$('#my_div').countdown(date1.getTime(), () =>{
  var id = $(this).attr("id");

  console.log(id);
  $.ajax({
    url: "set",
    type: "POST",
    data:{
      id: id
    },
    dataType: "JSON",
    success: function (jsonStr){
    }
  });
});

$('#my_div2').countdown(date2.getTime(), () =>{
  var id = $(this).attr("id");

  console.log(id);
  $.ajax({
    url: "set",
    type: "POST",
    data:{
      id: id
    },
    dataType: "JSON",
    success: function (jsonStr){
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div" data-id="1"></div>

<div id="my_div2" data-id="2"></div>

The counting is working good. Now I need to get data-id after the countdown finish. But getting value undefined. Also I need to print text Counting Done to each div my_div and my_div2. Something think like below:

$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime(), function(){
    callback: function() {
        $(this).text("Counting Done");
    }
});

My question is:

  1. How to get data-id for each div countdown?
  2. How to use callback as per my sample above?
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!