Javascript Adds Same Class To Divs Without Calculating For Each Div - javascript

I have 2 coupons showing, they both have the .new-coupon when in fact one should say .new-coupon and one should say .old-coupon. It seems to apply the same class for every element on the page with that class instead of calculating which class it should be for each element.
jQuery(document).ready(function($) {
// Set the date we're counting down to
var deadlineYear = $("#clockdiv .year").attr("rel");
var deadlineMonth = $("#clockdiv .month").attr("rel");
var deadlineDay = $("#clockdiv .days").attr("rel");
var deadlineHour = $("#clockdiv .hours").attr("rel");
var deadlineMinute = $("#clockdiv .minutes").attr("rel");
var deadlineSecond = $("#clockdiv .seconds").attr("rel");
var couponExpired = $("#clockdiv").attr("rel");
var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}
var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
var nowDateNew = new Date(now);
if (days <= 7) {
$('.couponDiv').addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
$('.couponDiv').addClass("new-coupon");
}
}, 1000);
});
HTML used for variables:
<div id="clockdiv" rel="'.$expired.'">
<span class="start" rel="'.$start.'"></span>
<span class="year" rel="'.$year.'"></span>
<span class="month" rel="'.$month.'"></span>
<div><span id="days" class="days" rel="'.$day.'"></span><div class="smalltext">Days</div></div>
<div><span id="hours" class="hours" rel="'.$hour.'"></span><div class="smalltext">Hours</div></div>
<div><span id="minutes" class="minutes" rel="'.$minute.'"></span><div class="smalltext">Minutes</div></div>
<div><span id="seconds" class="seconds" rel="'.$second.'"></span><div class="smalltext">Seconds</div></div>
</div>
HTML used for displaying the coupons on the offers page:
<li>
<?php
$year = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('Y');
$month = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('m');
$day = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('d');
$hour = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('H');
$minute = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('i');
$second = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('s');
$humanDate = DateTime::createFromFormat('Y-m-d H:i:s', get_field('offer_voucher_deadline'))->format('D jS M Y');
$expiredText = get_field('offer_voucher_expired');
?>
<div style="display:none;">
<?php echo do_shortcode('[gw-countdown expired="'.$expiredText.'" year="'.$year.'" month="'.$month.'" day="'.$day.'" hour="'.$hour.'" minute="'.$minute.'" second="'.$second.'" start="'.get_field('offer_voucher_start').'"]');?>
</div>
<div id="couponDiv" class="couponDiv">
<h1><?php the_title();?></h1>
<div class="couponDetails">
<div class="couponView">
<?php $offer = get_field('offer_single_label', 'options'); $offerC = ucwords($offer);?>
<a class="button" href="<?php the_permalink();?>" title="See Offer Details">See <?php echo $offerC;?> Details</a>
</div>
<div class="couponValid">
<p class="bold">Valid Until:</p>
<p class="couponDate"><?php echo $humanDate;?></p>
</div>
</div>
</div>
</li>
Edit
I understand completely where the issue lies, and have updated the code to the following:
$('.couponDiv').each(function() {
var startDate = $("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var newOldDate = new Date(startDateNew.setDate(startDateNew.getDate() + 7));
var nowDateNew = new Date(now);
if (days <= 7) {
$(this).addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
$(this).addClass("new-coupon");
}
});
However, I do not know how to make:
var startDate = $("#clockdiv .start").attr("rel");
Apply to $this so its $this #clockdiv .start because then it will work I believe...
Edit
I have altered a line of code to read:
var startDate = $(this).find("#clockdiv .start").attr("rel");
This now only adds the class to the first offer and not the 2nd offer, I then tried repeating the:
$(this).find()
Around the initial variables and then moved the:
$('.couponDiv').each(function() {
To the top below the document ready function however, this stopped any class being added.

if (days <= 7) {
$('.couponDiv').addClass("old-coupon");
} else if ((nowDateNew.getTime() - newOldDate.getTime()) < 0) {
$('.couponDiv').addClass("new-coupon");
}
In your codes above, you had selected all of .couponDiv to add class old-coupon and once again you select all of .couponDiv to add class new-coupon. The conditions have no meaning here because with any matching you still add class for all elements.
You must separate which elements are belong to "old" and with elements are belong to "new". Then add the respectively class name.

Is this what you need?
var startDate = $(this).find("#clockdiv .start").attr("rel"); //2018/09/28 17:00:00

After some reconstructing and work with $this I was able to get this working:
$('.couponWrap .coupons li').each(function() {
// Set the date we're counting down to
var deadlineYear = $(this).find("div .clockdiv .year").attr("rel");
var deadlineMonth = $(this).find("div .clockdiv .month").attr("rel");
var deadlineDay = $(this).find("div .clockdiv .days").attr("rel");
var deadlineHour = $(this).find("div .clockdiv .hours").attr("rel");
var deadlineMinute = $(this).find("div .clockdiv .minutes").attr("rel");
var deadlineSecond = $(this).find("div .clockdiv .seconds").attr("rel");
var couponExpired = $(this).find("div .clockdiv").attr("rel");
var countDownDate = new Date(deadlineYear + "/" + deadlineMonth + "/" + deadlineDay + " " + deadlineHour + ":" + deadlineMinute + ":" + deadlineSecond).getTime();
var startDate = new Date($(this).find("div .clockdiv .start").attr("rel"));
var self = $(this);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML= seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("clockdiv").innerHTML = "<p>" + couponExpired + "</p>";
}
//Works but only for 1st start date
//var testDate = $("div .clockdiv .start").attr("rel"); //2018/09/28 17:00:00
var startDateNew = new Date(startDate);
var startDateNewer = new Date(startDate);
var newOldDate = new Date(startDateNewer.setDate(startDateNew.getDate() + 7));
//alert(startDate + ", " + startDateNew + ", " + startDateNewer + ", " + newOldDate);
//This works fine
var nowDateNew = new Date().getTime();
//alert(nowDateNew - newOldDate.getTime());
if (days <= 7) {
self.find('div.couponDiv').addClass("old-coupon");
} else if ((nowDateNew - newOldDate.getTime()) < 0) {
self.find('div.couponDiv').addClass("new-coupon");
}
}, 1000);
});

Related

Countdown timer goes into negative numbers instead of replacing html

I made this countdown timer to show a video after it reaches the end. However it just goes into negative numbers. Seems to be related to the part of the code to hide the content after expiry date. Here is a JS fiddle
<div id="countdown"></div>
<div id="playsession"></div>
<script>
var releaseDate = new Date('05/29/2021 9:00 UTC+1');
var expiryDate = new Date('10/11/2021 01:00AM UTC+1');
var cdNotice = 'This session will appear automatically when the countdown finishes';
var trDay = ' Days';
var trHours = ' Hours';
var trMin = ' Minutes';
var trSec = ' Seconds';
var media = "<div class=\"wistia_responsive_padding\" style=\"padding:56.25% 0 0 0;position:relative;\"><div class=\"wistia_responsive_wrapper\" style=\"height:100%;left:0;position:absolute;top:0;width:100%;\"><iframe src=\"https:\/\/fast.wistia.net\/embed\/iframe\/eiwj630vxa?videoFoam=true\" title=\"June 19 & 20 ~ Refresh & Revive ~ Gen Rabten ~ 1 Video\" allow=\"autoplay; fullscreen\" allowtransparency=\"true\" frameborder=\"0\" scrolling=\"no\" class=\"wistia_embed\" name=\"wistia_embed\" allowfullscreen msallowfullscreen width=\"100%\" height=\"100%\"><\/iframe><\/div><\/div>\r\n<script src=\"https:\/\/fast.wistia.net\/assets\/external\/E-v1.js\" async><\/script>";
</script>
Above I set the start time and expiry time.
If the person loads the page before the countdown ends it should show the countdown. If the person loads after the countdown it will show the video.
If the person loads the page after the expiry time it should show the expired message.
Timer
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 = releaseDate - now;
var gone = expiryDate - now;
if (distance < 0 && gone > 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = "";
document.getElementById('playsession').innerHTML = media;
return;
}
if (gone < 0) {
clearInterval(timer);
document.getElementById('playsession').innerHTML = '<p>This video has now expired</p>';
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('countdown').innerHTML = '<p>' + cdNotice + '</p>';
document.getElementById('countdown').innerHTML += '<p>';
if (days > 0) {
document.getElementById('countdown').innerHTML += '<b>' + days + trDay + '</b> ';
}
if (hours > 0) {
document.getElementById('countdown').innerHTML += '<b>' + hours + trHours + '</b> ';
}
if (minutes > 0) {
document.getElementById('countdown').innerHTML += '<b>' + minutes + trMin + '</b> ';
}
document.getElementById('countdown').innerHTML += '<b>' + seconds + trSec +'</b>';
document.getElementById('countdown').innerHTML += '</p>';
}
timer = setInterval(showRemaining, 1000);
Your expire date is incorrect, add space before AM, then it will work, otherwise your condition is not met, because gone = NaN.
With this it works correctly:
var expiryDate = new Date('10/11/2021 01:00 AM UTC+1')

Countdown days, hours, minutes, seconds-made script jquery

How can I have a countdown timer with predetermined time?
My code
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var seconds = 6;
var minutes = 1;
function calculate() {
setTimeout(calculate, 1000);
$('#showDate').html(' expires after ' + minutes + ' minutes ' + seconds + ' seconds ');
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
minutes = 0;
seconds = 0;
}
}
}
calculate();
});
</script>
</head>
<body>
<div id='showDate'></div>
</body>
</html>
The above code applies only to minutes and seconds. How can I add hours and days?
Edited based on the method that was already being used.
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var days = 4;
var hours = 0;
var minutes = 0;
var seconds = 6;
function calculate() {
setTimeout(calculate, 1000);
$('#showDate').html(' expires after ' + days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds ');
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
if (minutes < 0) {
hours--;
minutes = 59;
if (hours < 0) {
days--;
hours = 23;
if (days < 0) {
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
}
}
}
}
}
calculate();
});
</script>
</head>
<body>
<div id='showDate'></div>
</body>
</html>
<html>
<head>
</head>
<body>
<div id="clockdiv">
expires after <span class="days"></span> day <span class="hours"></span> hours <span class="minutes"></span> minutes <span class="seconds">0</span> seconds
<script type="text/javascript">
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
</script>
</body>
</html>

Count Down Timer shows NaN

I'm having a problem with a count down timer made in JavaScript. It was working for the last 2 weeks, but today it started to show NaN:NaN... , and I can't understand why. Here is the code, does anyone have any idea which one could be the problem?
<div id="countdownmain">
<span id="countdownmain" class="timer"></span>
</div>
<script>
var date = new Date;
var secondsnow = date.getSeconds();
var minutesnow = date.getMinutes();
var hournow = date.getHours();
var day = date.getDay();
var passatti = (secondsnow + (minutesnow*60) + (hournow*3600));
if((day==1)||(day==2)||(day==3)||(day==4)){
if(passatti < 46800){
var upgradeTime = 46800 - passatti;
}else if(passatti > 46800){
var upgradeTime = 86400 - passatti + 46800;
}
}else if((day==5)&&(passatti < 46800)){
var upgradeTime = 46800 - passatti;
}else if((day==5)&&(passatti > 46800)){
var upgradeTime = 86400 - passatti + 46800 + 86400 + 86400;
}else if((day==6)){
var upgradeTime = 86400 - passatti + 46800 + 86400;
}else if((day==7)){
var upgradeTime = 86400 - passatti + 46800;
}
var seconds = upgradeTime;
function timer() {
var now = Math.floor(Date.now() / 1000);
('0' + 11).slice(-2)
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;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdownmain').innerHTML = "<span class='timesm'> For same working day dispatch, order in </span><br class='appear'><span style='display:inline-block; width:45px;'><span class='hideDays glowW'>" + ('0' + days).slice(-2) + "</span></span><span class='times'> days </span><span style='display:inline-block; width:45px;'><span class='hideHours glowW'>" + ('0' + hours).slice(-2) + "</span></span><span class='times'> hours </span><span style='display:inline-block; width:45px;'><span class='hideMinutes glowW'>" + ('0' + minutes).slice(-2) + "</span></span><span class='times'> minutes </span><span style='display:inline-block; width:45px;'><span class='hideSec glowW'>" + ('0' + remainingSeconds).slice(-2) + "</span></span><span class='times'> seconds </span>";
if (seconds == 0) {
clearInterval(countdownTimer);
//document.getElementById('countdownmain').innerHTML = "Completed";
seconds = upgradeTime;
} else {
seconds--;
$('.hideSec').fadeOut('slow');
}
if(('0' + remainingSeconds).slice(-2)==00){
$('.hideMinutes').fadeOut('slow');
}
if((('0' + minutes).slice(-2)==00)&&(('0' + remainingSeconds).slice(-2)==00)){
$('.hideHours').fadeOut('slow');
}
if((('0' + hours).slice(-2)==00)&&(('0' + minutes).slice(-2)==00)&&(('0' + remainingSeconds).slice(-2)==00)){
$('.hideDays').fadeOut('slow');
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
Unfortunately, today is Sunday! Javascript return 0 value as first of a week in getDay().
Take a look my fiddle. I just decreased day comparator value in if statement. (e.g. 1 -> 0, 2 -> 1, 3 -> 2 and so on..)

Restarting a timer from where it was when the user left the page

I have developed a JSP page. On this page, I have a count-down timer that displays time in hh:mm:ss. A link is provided to the previous page (page 2) from this page. After some work on page 2, control will be transferred to page 1 again.
I have a timer that starts when page 1 loads. When I go to page 2 and return to page 1, the timer gets refreshed. How can I make it start from where it was when I left the page?
Here's my timer code:
<script language="JavaScript">
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n ) {
return (n <= 9 ? "0" + n : n);
}
function getCurrentTime() {
time = new Date();
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
alert(hours + " " + mins + " " + secs);
}
function updateTimer() {
msLeft = endTime - (+new Date);
if ( msLeft < 999 ) {
alert("please save your work and send your file!");
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
secs = time.getUTCSeconds();
element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits(secs);
setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
}
if( hours == 0 && mins == 0 && secs == 59 ) alert("dsdsdsdsdsd");
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie ( name ) {
var cname = name + "=";
var dc = document.cookie;
if ( dc.length > 0 ) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
element = document.getElementById( elementName );
endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
updateTimer();
}
</script>
I think you can use cookies to store the current time and one flag=true before you switch to page 2; when you come back to page 1 you de-active flag=false to continue to calculate the time.
you can do follow steps below:
1) create a js file with content:
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
2) At form 1 before click to go to form 2, you can set the current time to cookie.
setCookie("tracking_time", time_string, 5);
Please refer Javascript Date Time functions to know how to get/set a time string
3) when come back to form 1 from form 2, you can get time value from cookie , then you set to timer to continue count time.
var time_string = getCookie("tracking_time");
Then you parse time_string to object
This is a sample complete code
<html>
<head>
</head>
<body>
<span id="countdown">Start</span>
<script>
function setCookie(key, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = key + "=" + value + expires + "; path=/";
}
function getCookie(key) {
var nameEQ = key + "=";
var ca = document.cookie.split(';');
for ( var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function removeCookie(key) {
setCookie(key, "", -1);
}
var countdown = document.getElementById("countdown");
var days, hours, minutes, seconds;
var target_date = getCookie("tracking_time");
if (target_date == null) {
target_date = new Date().getTime() + (2*60*60*1000); // set countdown 2 hours
}
function updateTimer() {
setInterval(function () {
// this line below will set to function that user click on link to go to form 2
setCookie("tracking_time", target_date, 1);
// End line
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
countdown.innerHTML = hours + "h: " + minutes + "m: " + seconds + "s";
}, 1000);
}
updateTimer();
</script>
</body>
</html>

how to replace old div with a new one?

I want to close and create a new div when the countdown hits 0. My div looks like this
<div id="bij2">Test
<div id="bij2Blauw">
<table width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td colspan="3" class="titel">Resterende tijd</td>
</tr>
<tr>
<td height="25" colspan="3" align="center" valign="middle">
<input id="aktie2" type="text" class="countdownTekst" size="27" readonly="readonly">
<script language="javascript">
countdown(2012, 7, 29, 'aktie2', 'bij2')
</script>
</td>
</tr>
<tr>
<td height="60">
<input name="kopen1" type="submit" class="kopen" id="kopen1" value="Koop nu"
/>
</td>
<td height="60" colspan="2" align="right" valign="bottom">
<span class="euro">€</span>
<span class="prijs">14,95</span>
</td>
</tr>
</table>
</div>
</div>
This is the countdown
function countdown(yr, m, d, idCountdown, divId) {
var theyear = yr;
var themonth = m;
var theday = d;
var today = new Date();
var todayy = today.getYear();
if (todayy < 1000) todayy += 1900
var todaym = today.getMonth();
var todayd = today.getDate();
var todayh = today.getHours();
var todaymin = today.getMinutes();
var todaysec = today.getSeconds();
var todaystring = montharray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec;
var futurestring = montharray[m - 1] + " " + d + ", " + yr;
var dd = Date.parse(futurestring) - Date.parse(todaystring);
var dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1);
var dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
var dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
var dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);
var dag = "dagen";
if (dday <= 0 && dhour <= 0 && dmin <= 0 && dsec <= 0) {
document.getElementById(idCountdown).value = "voorbij";
$(document.getElementById(divId)).fadeOut(2000);
//removeElements(document.getElementById(divId));
setTimeout("creatediv(document.getElementById(divId))", 3000);
return;
} else if (dday <= 1) {
dag = 'dag';
}
document.getElementById(idCountdown).value = dday + ' ' + dag + ' ' + dhour + " uur " + dmin + " min " + dsec + " sec";
setTimeout(function () {
countdown(theyear, themonth, theday, idCountdown);
}, 1000);
}
So when the time is over it will fade out the div using jQuery. Then i want to create a new div. I use this:
function creatediv(id) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.className = 'newclass';
newdiv.style.float = "left";
newdiv.innerHTML = "nothing";
document.body.appendChild(newdiv);
alert(id + 'gemaakt');
}
But this creates a div at the bottom of the page and i want a new one at the same position as the div that fades out. What do i need to change?
Have you tried the replaceWith of jQuery?
It's really simple:
$('#bij2').replaceWith( newcontent );
You are not using jQuery at all in your code. The error you make is that you don't replace the node but rather append the new one after it. The function you are looking for is replaceChild.
node.replaceChild(oldNode, newNode)
If you wan to replace div 2 with suppose a div 3
<div id="1"><div id = "2"></div></div>
you can use
$("#1").html('<div id="3"></div>')
or you can use
$("#2").replaceWith('<div id="3"></div>')
You've said "using jQuery," but you don't seem to be using jQuery.
If you really are using / intend to start using jQuery, then Rahul's answer is what you want.
If not, then you're looking for parentNode, insertBefore, and removeChild, e.g.:
// Assuming olddiv refers to the old div
var parent = olddiv.parentNode;
parent.insertBefore(newdiv, olddiv);
parent.removeChild(olddiv);
That inserts the new div in front of the old one, then removes the old one.
So perhaps:
function replacediv(oldid, id) {
var newdiv = document.createElement('div');
newdiv.id = typeof id !== "undefined" ? id : oldid; // Use old ID if no new one specified
newdiv.className = 'newclass';
newdiv.style.float = "left";
newdiv.innerHTML = "nothing";
var olddiv = document.getElementById(oldid);
var parent = olddiv.parentNode;
parent.insertBefore(newdiv, olddiv);
parent.removeChild(olddiv);
alert(id + 'gemaakt');
}
...and then call it with the old ID and the new one.
As a side note: You don't have to use setAttribute for id. It's a reflected property on the element instance.

Categories