strange error in javascript countdown - javascript

I'm building a webpage that shows multiple consecutive countdowns, depending from a text file.
Almost everything works now, only one thing still doesn't want to work.
The problem is this: when the timer hit's 00:00:00, it should switch to the next countdown, and start counting down, but what is does is showing some kind of glitch, it flashes between nan:nan:nan and 23:59:xx, like the countdown started again, counting down to the next day. I wrote some stuff to the console, and here I see that my function to set a new deadline in javascript is called, and the deadlinecounter does go up; but it goes up from 0 to 6 first, en later from 0 to 7. very strange I would say. Hope someone can help me!
this is my code:
<!DOCTYPE html>
<!-- php functions -->
<?php
$deadlineH = null;
$deadlineM = null;
$deadlineS = null;
$deadlineTitle = null;
$filename = "data.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$fullArray = setFullArray($content);
$length = count($fullArray);
for ($i = 0; $i < $length - 1; $i++) {
$value = $fullArray[$i];
echo "var " . ($i + 1) . ": " . $fullArray[$i] ." <br>";
if((($i+1) % 4) == 0){
echo " ";
}
}
$hoursArray = [];
$minutesArray = [];
$secondsArray = [];
$titlesArray = [];
setArrays($fullArray);
function setArrays($fullArray){
$length = count($fullArray);
for ($i=0; $i < $length - 1; $i = $i+4) {
array_push($GLOBALS['hoursArray'], $fullArray[$i]);
}
for ($j=1; $j < $length - 1; $j = $j+4) {
array_push($GLOBALS['minutesArray'], $fullArray[$j]);
}
for ($k=2; $k < $length - 1; $k = $k+4) {
array_push($GLOBALS['secondsArray'], $fullArray[$k]);
}
for ($l=3; $l < $length - 1; $l = $l+4) {
array_push($GLOBALS['titlesArray'], $fullArray[$l]);
}
}
$numberoflines = getNumberOflines($fullArray);
echo "number of lines: " . $numberoflines . "<br>";
showDeadlines($fullArray);
function setFullArray($content){
$fullArray = preg_split("/(:|\n)/" ,$content); // splits the whole data txt file into small chunks, everything apart
return $fullArray;
}
function getNumberOflines($fullArray){
$numberoflines = (sizeof($fullArray) - 1) / 4;
return $numberoflines;
}
function showDeadlines($fullArray){ // won't be used in final thing
$length = count($fullArray);
for ($i=0; $i < $length-1; $i = $i + 4) {
$deadlineNumber = ($i + 4)/4;
$deadlineH = $fullArray[$i];
$deadlineM = $fullArray[$i+1];
$deadlineS = $fullArray[$i+2];
$deadlineTitle = $fullArray[$i+3];
echo "deadline " . $deadlineNumber . ": " . $deadlineH . ":" . $deadlineM . ":" . $deadlineS . " titel : " . $deadlineTitle . "<br>";
}
}
function setDeadline($fullArray){
$length = count($fullArray);
for ($i=0; $i < $length-1; $i = $i + 4) {
$deadlineNumber = ($i + 4)/4;
$GLOBALS['deadlineH'] = $fullArray[$i];
$GLOBALS['deadlineM'] = $fullArray[$i+1];
$GLOBALS['deadlineS'] = $fullArray[$i+2];
$GLOBALS['deadlineTitle'] = $fullArray[$i+3];
}
}
?>
<!-- end php functions -->
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="startTime()">
<div id="visible">
<div id="clock"><span> </span> </div><br>
<div id="countdown"> </div>
<div id="countdown"> </div>
<div id="title"> </div>
</div>
<p>
<?php
echo json_encode($hoursArray);
echo json_encode($minutesArray);
echo json_encode($secondsArray);
echo json_encode($titlesArray);
?>
</p>
</div>
<!-- javascript scripts -->
<script>
var hoursArray = [];
var minutesArray = [];
var secondsArray = [];
var titlesArray = [];
var deadlineCounter;
function startTime() {
var now = new Date();
// year, month, day, hours, minutes, seconds, milliseconds
var deadline = new Date(2016, 11, 20, 00 ,00 ,00 ,00);
deadlineCounter = 0;
var clockH = now.getHours();
var clockM = now.getMinutes();
var clockS = now.getSeconds();
setArrays();
setInitialDeadline(deadline);
startClock('clock');
startCountdown('countdown', deadline);
var t = setTimeout(startTime, 500);
}
function setArrays(){
hoursArray= <?php echo json_encode($hoursArray); ?>;
console.log( hoursArray );
minutesArray= <?php echo json_encode($minutesArray); ?>;
console.log( minutesArray );
secondsArray= <?php echo json_encode($secondsArray); ?>;
console.log( secondsArray );
titlesArray= <?php echo json_encode($titlesArray); ?>;
console.log( titlesArray );
}
function setInitialDeadline(deadline) {
deadline.setHours(hoursArray[0]);
deadline.setMinutes(minutesArray[0]);
deadline.setSeconds(secondsArray[0]);
document.getElementById("title").innerHTML = titlesArray[0];
}
function setNewDeadline(deadline){
console.log('new deadline set');
deadline.setHours(hoursArray[deadlineCounter]);
deadline.setMinutes(minutesArray[deadlineCounter]);
deadline.setSeconds(secondsArray[deadlineCounter]);
document.getElementById("title").innerHTML = titlesArray[deadlineCounter];
}
function getCountdown(deadline){
var countdownTotal = Date.parse(deadline) - Date.parse(new Date());
var countdownS = Math.floor( (countdownTotal/1000) % 60 );
var countdownM = Math.floor( (countdownTotal/1000/60) % 60 );
var countdownH = Math.floor( (countdownTotal/(1000*60*60)) % 24 );
return{
'countdownTotal': countdownTotal,
'countdownH': countdownH,
'countdownM': countdownM,
'countdownS': countdownS
}
}
function startClock(id){
var clock = document.getElementById(id);
var timeInterval = setInterval(function(){
var now = new Date();
var nowH = now.getHours();
var nowM = now.getMinutes();
var nowS = now.getSeconds();
nowH = checkTime(nowH);
nowM = checkTime(nowM);
nowS = checkTime(nowS);
clock.innerHTML = nowH + ':' + nowM + ':' + nowS;
}, 1000);
}
function startCountdown(id, deadline){
var countdown = document.getElementById(id);
var timeInterval = setInterval(function(){
var t = getCountdown(deadline);
//console.log(t);
//console.log(deadlineCounter);
countdown.innerHTML = checkTime(t.countdownH) + ':' + checkTime(t.countdownM) + ':' + checkTime(t.countdownS);
if(t.countdownH == 0 && t.countdownM == 0 && t.countdownS == 0){
deadlineCounter++;
setNewDeadline(deadline);
t = getCountdown(deadline);
}
}, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
<!-- //end javascript -->
</body>
</html>
Thanks!

Correct calling the function startTime() inside itself like this: var t = setTimeout(startTime, 500);. Maybe it's better to remove this line from func body and write:
<body onload="setTimeout(startTime(), 500)">

Related

Submit span content to a database

Just for fun, I'm trying to build a simple time tracker; the page grabs a stored duration from a database, and you can then add more time to that value, and then store it back to the database.
The value is displayed in h:i:s format, but there's also a hidden span with the same time but just in seconds.
My problem:
I cannot figure out how to submit the contents of the span to the database.
If I instead put the hidden span contents inside a form input, then the content doesn't change; it just submits the original value back to the database.
I really feel like I'm making a bit of a meal out of this.
Here's the current code...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
//wip - for later - and remember to remove the injection!!!
if(sizeof($_POST) != 0){
$query = "UPDATE my_table SET t=SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$pdo->query($query);
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<div>
<div>
<span hidden id="tts"><?php echo $tts; ?></span>
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").text(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.querySelectorAll('div').forEach(div => {
div.querySelectorAll('span')
.forEach(span => console.log(span.textContent));
});
}
</script>
With CBroe's useful hint, the following works... although my attempts at preparing and binding $_GET are failing at the moment, so the query itself remains insecure...
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table (t TIME NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES ('00:01:50');
*/
require('path/to/connection/stateme.nts');
if(sizeof($_GET) != 0){
$query = "UPDATE my_table SET t = SEC_TO_TIME({$_GET['tts']}) LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
}
//Grab the stored value from the database
$query = "
select t
, time_to_sec(t) tts
, LPAD(HOUR(t),2,0) h
, LPAD(MINUTE(t),2,0) i
, LPAD(SECOND(t),2,0) s
from my_table
limit 1
";
if ($data = $pdo->query($query)->fetch()) {
$t = $data['t'];
$tts = $data['tts'];
$h = $data['h'];
$i = $data['i'];
$s = $data['s'];
} else {
$t = 0;
$tts = 0;
$h = '00';
$i = '00';
$s = '00';
}
?>
#relevant code starts here, I guess
<form id="myForm">
<input name="tts" type= "hidden" id="tts" value="tts">
<span id="hour"><?php echo $h; ?></span>:
<span id="min"><?php echo $i; ?></span>:
<span id="sec"><?php echo $s; ?></span>
<input id="startButton" type="button" value="Start/Resume">
<input id="pauseButton" type="button" value="Pause">
<button id="submit" onclick="myFunction()" >Save</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var Clock = {
totalSeconds: <?php echo $tts ?>,
start: function () {
if (!this.interval) {
var self = this;
function pad(val) { return val > 9 ? val : "0" + val; }
this.interval = setInterval(function () {
self.totalSeconds += 1;
$("#hour").text(pad(Math.floor(self.totalSeconds / 3600 % 60)));
$("#min").text(pad(Math.floor(self.totalSeconds / 60 % 60)));
$("#sec").text(pad(parseInt(self.totalSeconds % 60)));
$("#tts").val(pad(parseInt(self.totalSeconds)));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
resume: function () {
this.start();
}
};
$('#startButton').click(function () { Clock.start(); });
$('#pauseButton').click(function () { Clock.pause(); });
</script>
<script>
function myFunction() {
document.getElementById("myForm").submit();
}
}
</script>

Accessing an Array outside of a While loop

I have a while loop which contains an array which is referencing another file: legProductionAllRecords.php. This file returns an array Which is then used in the loop. I want to be able to use the $orderArray in my javascript tableObj as shown however it is not working. And shows no results when I have no results in $inProgressArray. I also need to be able to use $inProgressArray outside of this loop.
index.php
$madeAt = 2;
$inProgressQuery ="SELECT * FROM leg_prod_inprogress WHERE madeat=".$madeAt;
$inProgressResult = mysql_query($inProgressQuery);
$orderArray = array();
$inProgressArray = array();
while($inProgressArray = mysql_fetch_array($inProgressResult,MYSQL_ASSOC)) {
$inPogressOrder = "-1";
if ($inProgressArray != false) {
$inPogressOrderNo = $inProgressArray['purchase_no'];
} else {
$inPogressOrderNo = -1;
}
require_once('legProductionAllRecords.php');
$allArray = legProductionAllRecords($madeAt, $inPogressOrderNo);
$orderArray = $allArray['allOrder'];
$inPogressOrder = $allArray['inprocessOrder'];
$toadyFinishedOrder = $allArray['todayFinishedOrder'];
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var tableObj = {
data: <?php echo json_encode($orderArray); ?>,
processingData:<?php
if(!empty($inPogressOrder)&&$inPogressOrder!=''){
echo json_encode($inPogressOrder);
}
else{echo -1;} ?>,
}
</script>
</head>
</html>
legProductionAllRecords.php
<?php
function legProductionAllRecords($madeAt,$inPogressOrderNo){
$dayquery = "SELECT * FROM manufacturedat WHERE ManufacturedAtID=".$madeAt;//$madeAt is either 2 or 1
$dayresult = mysql_query($dayquery);
$dayArray = mysql_fetch_array($dayresult,MYSQL_ASSOC);
$day = $dayArray['LegCompletionNoItems'].' days';
$qry = "SELECT a.PURCHASE_No, a.legstyle, a.legfinish, a.LegQty, a.legheight, ".
"a.addlegstyle, a.addlegfinish, a.AddLegQty, a.ORDER_NUMBER, a.specialinstructionslegs, ".
"b.surname, b.first ".
"FROM purchase AS a LEFT JOIN contact AS b ON a.contact_no=b.CONTACT_NO ".
"WHERE a.legrequired='y' ".
"AND a.completedorders = 'n' ".
"AND a.quote = 'n' ".
"AND a.orderonhold = 'n' ".
"AND a.contact_no <> 326314 ".
"AND a.contact_no <> 324273 ".
"AND a.contact_no <> 313820 ".
"AND a.ORDER_DATE >= '2015-12-31' ".
"AND (a.cancelled IS NULL OR a.cancelled <> 'y') ";
$result = mysql_query($qry);
$orderArray = array();
$returnArray['inprocessOrder'] = null;
$returnArray['todayFinishedOrder'] = null;
while ($temp = mysql_fetch_array($result,MYSQL_ASSOC)){
if(!empty($temp)){
$temp['surname'] = mb_convert_encoding($temp['surname'],"UTF-8");
//$temp['title'] = mb_convert_encoding($temp['title'],"UTF-8");
$temp['first'] = mb_convert_encoding($temp['first'],"UTF-8");
$qcQuery = "SELECT * FROM qc_history WHERE ComponentID=7 AND Purchase_No=".$temp['PURCHASE_No']." ORDER BY QC_Date DESC";
$qcresult = mysql_query($qcQuery);
$temp2 = mysql_fetch_array($qcresult,MYSQL_ASSOC);
if($temp2['QC_StatusID']== 20 && $temp2['MadeAt']==$madeAt ){//$temp2['QC_StatusID']== 20 &&
//=====================Change the date format to week:day===============================//
$temp2['formatedBCWExpected'] = date('d/m/Y',strtotime($day,strtotime($temp2['BCWExpected'])));
$tep_time = date_sub(date_create($temp2['BCWExpected']),date_interval_create_from_date_string($day));
$time = explode(':',date_format($tep_time,'W:w'));
$week = (int)$time[0];
$weekday = (int)$time[1];
if($weekday == 0){
$weekday = 5;
}
if($weekday == 6){
$weekday = 5;
}
$temp2['WDdate'] = $week.':'.$weekday;
//=======================End of Change the date format to week:day===============================//
$temp['qc_history'] = $temp2;
$temp['cname'] = $temp['first'].' '.$temp['surname'];
if($temp['PURCHASE_No'] == $inPogressOrderNo){
$returnArray['inprocessOrder'] = $temp;
}
else{
array_push($orderArray, $temp);
}
}
}
}
$returnArray['allOrder'] = $orderArray;
return $returnArray;
}
?>
I have tried the following:
I have used this answer to understand how to reference and update an array outside of a while loop
I have tried including a check for whether $inProgressArray is empty in the while loop like this.
while($inProgressArray = mysql_fetch_array($inProgressResult,MYSQL_ASSOC)||empty($inProgressArray))
however, there is an item in leg_prod_inprogress and it's not shown in the $inProgressArray outside the loop.
Editted 16/11/17 16:13 GMT: Added the details of legProductionAllRecords.php
Editted 2 17/11/17 08:43 GMT: Added the return statement of the return array of the function

Javascript Timer Issues

I am setting up a timer on an array of dynamic data taken from a db. It works but when I click the button for a second time it makes the seconds increment really quickly. I would also like to set the initial count back to 60 each time the button is clicked. Can anyone help? My code so far is as follows:
<script>
var counts = [];
var xs = [];
for (var i = 1; i < 61; i++) {
counts.push(61);
xs.push(0);
};
function timer(id) {
xs[id] = setTimeout("timer(" + id + ")", 1000);
counts[id] = counts[id] - 1;
if (counts[id] < 1) { counts[id] = 0; }
document.getElementById("but" + id).innerHTML = counts[id];
}
function restarttimer(id) {
xs[id] = setTimeout("timer(" + id + ")", 1000);
counts[id] = counts[id] - 1;
if (counts[id] < 1) { counts[id] = 0; }
document.getElementById("but" + id).value = counts[id];
}
</script>
<?php
$i=1;
?>
<table id="itemTable"><tr>
<?php
while($r=mysql_fetch_array($resultSearch))
{
?>
<td>
<p id="but<?php echo $r['itemID'];?>">>
</p>
<input type="button" value="bid" onclick="timer(<?php echo $r['itemID'];?>)" />
</td>
<?php
if($i % 3 == 0)
echo '</tr><tr>';
$i++;
}
?>

Toggle to open/close tabbed navigation

I am very new to jQuery/Javascript and have been trying to have a tabbed navigation menu closed on page load then open if clicked by the user. So far I haven't had any joy with editing the following file
function amshopby_start(){
$$('.block-layered-nav .form-button').each(function (e){
e.observe('click', amshopby_price_click_callback);
});
$$('.block-layered-nav .input-text').each(function (e){
e.observe('focus', amshopby_price_focus_callback);
e.observe('keypress', amshopby_price_click_callback);
});
$$('a.amshopby-more', 'a.amshopby-less').each(function (a){
a.observe('click', amshopby_toggle);
});
$$('span.amshopby-plusminus').each(function (span){
span.observe('click', amshopby_category_show);
});
$$('.block-layered-nav dt').each(function (dt){
dt.observe('click', amshopby_filter_show);
});
$$('.block-layered-nav dt img').each(function (img){
img.observe('mouseover', amshopby_tooltip_show);
img.observe('mouseout', amshopby_tooltip_hide);
});
$$('.amshopby-slider-param').each(function (item) {
param = item.value.split(',');
amshopby_slider(param[0], param[1], param[2], param[3], param[4], param[5], param[6]);
});
}
function amshopby_price_click_callback(evt) {
if (evt && evt.type == 'keypress' && 13 != evt.keyCode)
return;
var prefix = 'amshopby-price';
// from slider
if (typeof(evt) == 'string'){
prefix = evt;
}
else {
var el = Event.findElement(evt, 'input');
if (!Object.isElement(el)){
el = Event.findElement(evt, 'button');
}
prefix = el.name;
}
var a = prefix + '-from';
var b = prefix + '-to';
var numFrom = amshopby_price_format($(a).value);
var numTo = amshopby_price_format($(b).value);
if ((numFrom < 0.01 && numTo < 0.01) || numFrom < 0 || numTo < 0) {
return;
}
var url = $(prefix +'-url').value.gsub(a, numFrom).gsub(b, numTo);
amshopby_set_location(url);
}
function amshopby_price_focus_callback(evt){
var el = Event.findElement(evt, 'input');
if (isNaN(parseFloat(el.value))){
el.value = '';
}
}
function amshopby_price_format(num){
num = parseFloat(num);
if (isNaN(num))
num = 0;
return Math.round(num);
}
function amshopby_slider(width, from, to, max_value, prefix, min_value, ratePP) {
width = parseFloat(width);
from = parseFloat(from);
to = parseFloat(to);
max_value = parseFloat(max_value);
min_value = parseFloat(min_value);
var slider = $(prefix);
// var allowedVals = new Array(11);
// for (var i=0; i<allowedVals.length; ++i){
// allowedVals[i] = Math.round(i * to /10);
// }
return new Control.Slider(slider.select('.handle'), slider, {
range: $R(0, width),
sliderValue: [from, to],
restricted: true,
//values: allowedVals,
onChange: function (values){
this.onSlide(values);
amshopby_price_click_callback(prefix);
},
onSlide: function(values) {
var fromValue = Math.round(min_value + ratePP * values[0]);
var toValue = Math.round(min_value + ratePP * values[1]);
/*
* Change current selection style
*/
if ($(prefix + '-slider-bar')) {
var barWidth = values[1] - values[0] - 1;
if (values[1] == values[0]) {
barWidth = 0;
}
$(prefix + '-slider-bar').setStyle({
width : barWidth + 'px',
left : values[0] + 'px'
});
}
if ($(prefix+'-from')) {
$(prefix+'-from').value = fromValue;
$(prefix+'-to').value = toValue;
}
if ($(prefix + '-from-slider')) {
$(prefix + '-from-slider').update(fromValue);
$(prefix + '-to-slider').update(toValue);
}
}
});
}
function amshopby_toggle(evt){
var attr = Event.findElement(evt, 'a').id.substr(14);
$$('.amshopby-attr-' + attr).invoke('toggle');
$('amshopby-more-' + attr, 'amshopby-less-' + attr).invoke('toggle');
Event.stop(evt);
return false;
}
function amshopby_category_show(evt){
var span = Event.findElement(evt, 'span');
var id = span.id.substr(16);
$$('.amshopby-cat-parentid-' + id).invoke('toggle');
span.toggleClassName('minus');
Event.stop(evt);
return false;
}
function amshopby_filter_show(evt){
var dt = Event.findElement(evt, 'dt');
dt.next('dd').down('ol').toggle();
dt.toggleClassName('amshopby-collapsed');
Event.stop(evt);
return true;
}
function amshopby_tooltip_show(evt){
var img = Event.findElement(evt, 'img');
var txt = img.alt;
var tooltip = $(img.id + '-tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.className = 'amshopby-tooltip';
tooltip.id = img.id + '-tooltip';
tooltip.innerHTML = img.alt;
document.body.appendChild(tooltip);
}
var offset = Element.cumulativeOffset(img);
tooltip.style.top = offset[1] + 'px';
tooltip.style.left = (offset[0] + 30) + 'px';
tooltip.show();
}
function amshopby_tooltip_hide(evt){
var img = Event.findElement(evt, 'img');
var tooltip = $(img.id + '-tooltip');
if (tooltip) {
tooltip.hide();
}
}
function amshopby_set_location(url){
if (typeof amshopby_working != 'undefined'){
return amshopby_ajax_request(url);
}
else {
return setLocation(url);
}
}
document.observe("dom:loaded", function() { amshopby_start(); });
The element that I am trying to manipulate is contained in this file
<?php if($this->canShowBlock()): ?>
<div class="block block-layered-nav">
<div class="block-title">
<strong><span><?php echo $this->__('Shop By') ?></span></strong>
</div>
<?php echo $this->getStateHtml() ?>
<div class="block-content">
<?php if($this->canShowOptions()): ?>
<!-- <p class="block-subtitle">--><?php //echo $this->__('Shopping Options') ?><!--</p>-->
<ul id="narrow-by-list">
<li>
<?php $_filters = $this->getFilters() ?>
<?php foreach ($_filters as $_filter): ?>
<?php if($_filter->getItemsCount()): ?>
<div class="opt-row">
<dl class="opt-row">
<dt><?php echo $this->__($_filter->getName()) ?></dt>
<dd><?php echo $_filter->getHtml() ?></dd>
</dl>
</div>
<?php endif; ?>
<?php endforeach; ?>
</li>
</ul>
<script type="text/javascript">decorateDataList('narrow-by-list')</script>
<?php endif; ?>
<?php if ($this->getLayer()->getState()->getFilters()): ?>
<div class="actions"><?php echo $this->__('Clear All') ?></div>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
When the page loads I woul like to have the tabbed navigation menus closed but toggable to open by the user... Can anyone assist please?
From the admin panel, you can make any of your filters closed by default:-
Catalog > Improved Navigation > Filters
Select the relevant filter and set 'Collapsed' to 'Yes'.

multiple records using the same script

I have built a voucher website, where each voucher has a countdown timer. When you view a voucher the countdown works fine, however...
I also have a summary page with multiple vouchers (using a repeat region on the recordset)... when I apply the script to each of the vouchers the script doesn't work.
The HMTL:
<h3 class="remaining"><?php echo $row_rs_dealItem['dateend']; ?> remaining</h3>
The JAVASCRIPT external file:
$(document).ready(function(){
$('.remaining').each(function(){
var expiry_date = Date.createFromMysql($(this).html());
var current_date = new Date();
console.log(expiry_date.getTime() );
console.log(current_date.getTime());
if (expiry_date.getTime() > current_date.getTime()) {
var time_diff = Math.floor((expiry_date.getTime() - current_date.getTime()) / (1000*60*60));
console.log(expiry_date.getTime() - current_date.getTime());
console.log(time_diff);
days_diff = Math.floor(time_diff / 24);
hours_diff = time_diff % 24;
$(this).html(days_diff + ' days ' + hours_diff + ' hours');
}
else{
$(this).html('expired');
}
});
});
Date.createFromMysql = function(mysql_string)
{
if(typeof mysql_string === 'string')
{
var t = mysql_string.split(/[- :]/);
//when t[3], t[4] and t[5] are missing they defaults to zero
return new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
}
return null;
}
The JAVASCRIPT inline:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="scripts/script.js"></script>
<script type="text/javascript">
var reference = '<?php echo $row_rs_dealItem['reference']; ?>';
var today = Date.createFromMysql('<?php echo date('Y-m-d h:i:s'); ?>');
var contractstarts = <?php echo ($row_rs_dealItem['datestart'] == '0000-00-00') ? '""' : 'Date.createFromMysql("' . $row_rs_dealItem['datestart'] . '")'; ?>;
var contractexpires = <?php echo ($row_rs_dealItem['dateend'] == '0000-00-00') ? '""' : 'Date.createFromMysql("' . $row_rs_dealItem['dateend'] . '")'; ?>;
</script>
I hope this is enough data for you.
thanks
I realised that I had effectively copied the code from one page to another and the record sets had different names :(

Categories