how to replace old div with a new one? - javascript

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.

Related

Javascript Adds Same Class To Divs Without Calculating For Each Div

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);
});

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..)

How do I make sure my function works for my variable?

function numberToTime(num){
var d = 0, h = 0, m = 0;
var numToMinutes = num*60;
while(numToMinutes > 59){
numToMinutes -= 60;
h++;
if(h > 23){
h-= 24;
d++;
}
m = numToMinutes;
}
if( d > 0){
return d + " days " + h + " hours " + m +" minutes ";
}else{
return h+":"+m;
}
This code was given to me by a very nice user here on Stack Overflow.
Since I am very new to programming, especially JavaScript I have no idea where to put my variable. I have a var howLong = (0,1 * amount + 0,2 * time) I want to convert it to hours and minutes with the code above, but I don't know how to tell the function it's about var howLong.
Can somebody help me out?
May be like this?
var ndays = Math.floor(sec/86400);
var nhours = Math.floor((sec%86400)/3600);
var nminutes = Math.floor(((sec%86400)%3600)/60);
var nseconds = ((sec%86400)%3600)%60;
return ndays + " days " + nhours + " hours " + nminutes + " minutes " + nseconds + " seconds";

creating a log with append

need to create a log of messages where the message be saved along with the time.
I have this code, but the acresentar a new message is deleted the old and replaced by the new.
var textons = prompt("Digite sua mensagem para a ONS", "");
var areaons = prompt("Digite a area onde o problema ocorreu", "");
var date = new Date();
var d = date.getDate();
var day = (d < 10) ? '0' + d : d;
var mes = date.getMonth() + 1;
var month = (mes < 10) ? '0' + mes : mes;
var yy = date.getYear();
var year = (yy > 100) ? yy - 100 : yy;
var hours = date.getHours();
var min = date.getMinutes();
var minutes = (min < 10) ? '0' + min : min;
var sec = date.getSeconds();
var seconds = (sec < 10) ? '0' + sec : sec;
if (areaons != null && textons != null) {
document.getElementById("logdescricao").innerHTML =
"ONS: " + textons;
document.getElementById("logarea").innerHTML =
areaons;
document.getElementById("loghoracos").innerHTML =
day + "/" + month + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
document.getElementById("loghoralocal").innerHTML =
day + "/" + month + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
}
}
I thought about using the .append (function) but did not succeed.
how can I make the text stop being rewritten and pass to get saved?
thank
If I've understood you correctly, you just want it to add to each section in stead of overwriting?
Then all you have to do is "+=" instead of "="
document.getElementById("logdescricao").innerHTML += "ONS: " + textons
However, this is probably not the best way of doing this.
You could try:
var logdescricaoText = document.createTextNode("ONS: "+textons);
document.getElementById("logdescricao").appendChild(logdescricaoText);
But, really, if you want to make a list of things, then you should be using a table. This will allow for much neater and structured styling.
In your HTML:
<table>
<thead>
<tr>
<td>Descricao</td>
<td>LogMessage</td>
<!-- other field headers like 'time' -->
</tr>
</thead>
<tbody id=logs>
</tbody>
</table>
Then you can use the javascript (inside your 'if' block, instead of all your ".innerHTML =" stuff)
var logLine = document.createElement("tr");
document.getElementById("logs").appendChild(logLine);
var descricao = document.createElement("td");
descricao.appendChild(document.createTextNode("ONS: "+textons));
logLine.appendChild(descricao);
var logArea = document.createElement("td");
logArea.appendChild(document.createTextNode(areaons);
logLine.appendChild(logArea);
etc..
Additionally, you might want to apply a CSS styling to the 'thead' part of the HTML
eg. in your CSS file:
thead {
font-weight: bold;
}

jQuery Time difference

Hi am making some time calculation in jquery. Do you think am using the best way?
<table width="100%" border="0" cellpadding="0">
<tr>
<td>Departure Time</td>
<td>Arrival Time</td>
<td>Difference</td>
</tr>
<tr>
<td><input name="departure" type="text" class="std1" id="departure" size="10" alt="time"/></td>
<td><input name="arrival" type="text" class="std1" id="arrival" size="10" alt="time"/></td>
<td><input name="duration" type="text" class="std" id="duration" size="10" readonly="readonly" alt="time"/></td>
</tr>
</table>
function hour2mins(timestr) {
var spltd = timestr.split(":");
if (spltd.length == 2) {
return parseInt(parseInt(spltd[0] * 60) + parseInt(spltd[1]));
} else {
return false;
}
}
function mins2hour(instr) {
var hourstr = parseInt(instr / 60);
if (hourstr.toString().length == 1) {
hourstr = "0" + (hourstr + '');
}
var minstr = parseInt(instr % 60);
if (minstr.toString().length == 1) {
minstr = "0" + (minstr + '');
}
return hourstr + ':' + minstr;
}
function tdiff(t1, t2) {
var t1 = hour2mins(t1);
var t2 = hour2mins(t2);
var ret = mins2hour(parseInt(t2 - t1));
if (t2 < t1) {
ret = mins2hour(parseInt(parseInt(t2 + 1440) - t1));
}
return ret;
}
$(function() {
$("input.std1").keyup(function(b) {
$("#duration").val(tdiff($("#departure").val(), $("#arrival").val()));
});
});
link : http://jsfiddle.net/xmQD7/1/
Your code won't work for the following input: "07:09", "07:07". The problem is with your parseInt statement.
You should always pass in 10 as the second parameter, so that it's parsed as a decimal value.
return parseInt(parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10));
Also, you don't need to wrap the addition of two parsed integers in a parseInt, so that would be just
return parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10);
In mins2hour, you don't need a parseInt here:
var hourstr = parseInt(instr / 60);
and here:
var minstr = parseInt(instr % 60);
I'm guessing you wanted a string as this point (as your var name suggests), so that should have been
var hourstr = "" + (instr / 60);
var minstr = "" + (instr % 60);
There are a few more unnecessary uses of parseInt in your code. I suggest you read the documentation on parseInt - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Categories