How to call a javascript function like a "onload"?
I mean. I'm trying to call a CountDownTimer() function but I don't know how to do it. Can someone help me?
Ps. The javascript function is working fine.
At my view I'm trying this way:
@foreach (var item in Model.pedidosAberto)
{
<div class="col-lg-6 mb-4">
<a href="#" data-toggle="modal" data-id="@item.IdPedido" data-partial="_AbertoPartial"
data-modal="#Modal" class="card bg-success text-white text-decoration-none">
<div class="card-body">
<div class="float-right">
<div id="[email protected]"></div>
<script type="text/javascript">
CountDownTimer('06/12/2021 4:45 PM', '[email protected]');
</script>
</div>
</div>
</a>
</div>
}
At the same view I have this:
@section scripts{
<script type="text/javascript">
$(document).ready(function () {
//CountDownTimer('06/12/2021 4:45 PM', 'countdown');
function CountDownTimer(dt, id) {
var end = new Date(dt);
alert(end);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'EXPIRED!';
return;
}
//var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
//document.getElementById(id).innerHTML = days + 'days ';
document.getElementById(id).innerHTML = hours + ':';
document.getElementById(id).innerHTML += minutes + ':';
document.getElementById(id).innerHTML += seconds;
}
timer = setInterval(showRemaining, 1000);
}
});
</script>
CountDownTimeris not exposed globally because it's defined in the function passed toready(). Remove$(document).ready(function () {and});. Note that your count down may not work as you'd like, because a) the format of the date you're passing tonew Date(string)is not one of the formats defined in the spec and therefore is dependent on the browser and b) the element with the id may not exist yet (although it should, since you don't callshowRemainingfor a second).