Home > Mobile >  jQuery/Javascript print the value from return function
jQuery/Javascript print the value from return function

Time:06-23

How to return value from function to html element.

Below is the sample code:

$.fn.countdown = function(toTime){
  var x = 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);

    var value = days   "d "   hours   "h "   minutes   "m "   seconds   "s ";
    console.log(value);
    return value;
  }, 1000);
};

$('#my_div').countdown(new Date("Jan 5, 2024 15:37:25").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I need the result value from that function print to #my_div.

CodePudding user response:

The issue is because your return statement is inside the setInterval() handler and is therefore not returned from the $.fn.countdown invocation.

You instead need to reference the element which your jQuery extension library was instantiated on, using the this keyword, and then update that element. In the example below I used the text() method.

$.fn.countdown = function(toTime) {
  let $el = $(this);
  
  let timeUpdate = () => {
    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);

    var value = days   "d "   hours   "h "   minutes   "m "   seconds   "s ";
    $el.text(value);
  }
  
  timeUpdate(); // run on instantiation
  var intervalId = setInterval(timeUpdate, 1000); // run every second
};

$('#my_div').countdown(new Date("Jan 5, 2024 15:37:25").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>

  • Related