i work on a handicrafts auction website, so there is a special auction countdown (javascript timer) for each product, the timer work well for each product when i display the product details page
but when using foreach; it doesn't display except for the last product; and in the place of first product timer!!
you can check the result and the auction finish of each product
@extends('layouts.main_layout')
@section('content')
<div class="RecentAuction">
<div class="container">
<div class="RecentAuction-content">
<h2 class="p-2">Recent Auctions</h2>
<div class="row">
@foreach($products as $product)
<div class="col-3 col-3 mb-4 mt-4">
<div class="card">
<div id="countdown" class="timer text-center">
{{-- timer here --}}
</div>
<a href="{{route('product.details', $product->id) }}">
<img src="{{asset('/HandicraftsAuction/image/wool.jpg')}}" class="card-img-top">
</a>
<div class="card-body">
<h5 class="text-center">{{$product->title}}</h5>
<div class="d-flex justify-content-between">
<span>MaxBid: {{$product->orderNowPrice}}$</span>
</div>
{{-- complement here --}}
</div>
</div>
</div>
@endforeach
</div>
</div>
</div>
@endsection
@section('script')
<script>
var seconds = {!! json_encode($product->remainingTime(), JSON_HEX_TAG) !!};
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":"
+ pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Expired";
location.reload();
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
@endsection
i think the problem is in passing laravel to javascript as js can't manipulate dynamic div content counter for each product using #id. however, using class instead doesn't make sense also!.