Javascript not running Prestashop - javascript

Im trying to add a countdowns shipping time, using this code: http://jsfiddle.net/37ox54bk/7/
I use the HTML box module: https://mypresta.eu/modules/front-office-features/html-box.html
The code looks like this:
<div id="countdownTimer">0</div>
<script type="text/javascript">// <![CDATA[
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var target = 15; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}//keep this before the sunday, trust me :>
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if((weekday>=1) && (weekday<=5)){
if (now.getHours() > target) { //stop the clock
return 0;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
}// ]]></script>
But nothing is happening, it just shows 0 like the javascript is not running.
Anyone got any idea?

It looks like that module wraps everything inside <script> tags in
// <![CDATA[
//--><![CDATA[//><!-- //
[your code]
//--><!
// ]]>
It doesn't look like that's even the correct way to use CDATA but in any case i think all this achieves in your case is commenting the whole piece of code out.
Do you not have access to the files in your theme? You could for instance still add the <div id="countdownTimer">0</div> with the module and paste your code into the document.ready(); function of the globals.js

Try to make a js file and link it like this:
<script src="http://yoursite.com/folder/file.js"></script>
<div id="countdownTimer">0</div>
And if you need to add some css code you have to add it on your current css prestashop file (for example if you need to add it on your homepage so you've to work on golbal.css)
Hope it can help you

Related

How add PHP code to my countdown javascript code for add data to MySQL column automatically after countdown finished?

This is my countdown javascript code everyday on 23:00 of local time will finish and after 1 hour again will start to countdown for tomorrow and this continues. I wanted to know is it possible to add PHP code to this till after countdown finished everyday It adds "5" to my "Credit" column ("Credit" + 5 ) in my MySQL automatically ? appreciate for any kind of guidance.
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'Your match started!';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(23,0,0,0);
var myEnd = new Date()
myEnd.setHours(24,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<font face="Trebuchet MS">
<div id="foo" style="color: white; font-size: 14px; font-weight: bold;"></div>
Jquery Ajax is the way to go here i guess.
It seems like you are very new and might not know what ajax is.
In short with Ajax you can call a webpage url in the background. So You could call www.yourdomain.com/addCredits.php
It will do the same as if you would visit that url in your browser. Just write your SQL Code inside that addCredits.php File and you're done.
Just add something like this to your javascript:
$.ajax({url: "addCredits.php"});
You will have to embed jquery inside your document first though.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
And also you might want to wait for that script to load before you call that function:
$( document ).ready(function() {
$.ajax({url: "addCredits.php"});
});
Edit:
Your Counter acutally seems to continue in a loop since it keeps up calling itself in the end.
But i would say just put it where your setTimeout is at the end of your function.
Edit2:
Here is an Example with a Clock, your code seems to be over-complicated to be honest. It doesn't really work when i put it in a fiddle aswell...
You could just use this instead:
function startTime() {
// set time variables h=hour, m=minute, s=second
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//check if 0's have to be added for better appearance. no logical use!
m = checkTime(m);
s = checkTime(s);
//display current time on the element with id="txt"
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
//check if its 23:00:00 ... if so call addCredits.php
if(h == 23 && m == 00 && s == 00) {
$.ajax({url: "addCredits.php"});
}
//restart this function every second to update the clock
var t = setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

Change CSS of HTML on computer timing

I have three CSS with me in one HTML, morning.css, evening.css & night.css..
My requirement is that, once visitor visits the website, the css should change according to visitor PC timing...
Morning.css --> 6.00hrs - 15.00hrs
Evening.css --> 15.00hrs - 19.00 hrs
Night.css --> 19.00hrs - 6.00hrs
Can anyone help me with this..??? My requirement is on load not on button click
You can write a function which will set the class to body like the following:
function setTimingClass() {
var hour = new Date().getHours();
var cls;
if (hour >= 6 && hour <= 14) {
cls = 'morning';
} else if (hour >= 15 && hour <= 18) {
cls = 'evening';
} else {
cls = 'night';
}
document.body.className = document.body.className + ' ' + cls;
}
And call the function on body's onload. And then use this classes in your css file to style accordingly
You can use for example function like this:
function applyClass(){
var date = new Date();
var hour = date.getHours();
if(hour >= 6 && hour < 15) {
// apply 'morning' class to body
} else if(hour >= 15 && hour < 19) {
// apply 'evening' class to body
} else {
// apply 'night' class to body
}
}
How to append class to DOM element you can easily find on another thread of stackoverflow
With this function you can check time and class to the dom element
(function(){
var currentdate = new Date();
var datetime = currentdate.getHours();
if(datetime >=6 && datetime<15){
// moning class
}
else if(datetime >=15 && datetime<19){
// evening classes
}
else{
// night class
}
alert(datetime)
}());
jsfiddle
You need to use JS or any other programming language like php to achieve this.
For me easiest way will be loading all 3 scripts and adding class to body depands on hour.
<script>
window.onload = function(){
var d = new Date();
var h = d.getHours();
if(h >= 6 && <= 15) {
document.body.setAttribute('class','morning');
}
}
</script>

How to Make A Countdown Timer And Update MySQL Record When The Time is Up?

I need help on how to update MySQL table when time is up? I got this code:
<script language="JavaScript">
var timeleft;
var nextdue;
var tick = 1000;
function parseTime(t) {
var tt = ("0:00:" + t);
tt = tt.split(":").reverse();
return (tt[0] * 1000) + (tt[1] * 60000) + (tt[2] * 3600000);
}
function zeroPad(n) {
if (n < 10) return "0" + n;
return "" + n;
}
function makeTime(t) {
if (t < 0) return "0:00:00";
var tt = t + 999;
return Math.floor(tt / 3600000) + ":" +
zeroPad(Math.floor(tt / 60000) % 60) + ":" +
zeroPad(Math.floor(tt / 1000) % 60);
}
function startTimer() {
nextdue = new Date().getTime();
timeleft = parseTime(document.timerform.timerbox.value);
runTimer();
}
function runTimer() {
document.timerform.timerbox.value = makeTime(timeleft);
if (timeleft <= 0) alert("Time's up!");
else {
var timecorr = (new Date().getTime()) - nextdue;
if (timecorr > 0 && timecorr < 3000) {
timeleft -= (tick + timecorr);
nextdue += tick;
if (timeleft < 1) setTimeout("runTimer()", tick + timeleft);
else setTimeout("runTimer()", Math.max(1, tick - timecorr));
}
else {
nextdue = (new Date().getTime()) + tick;
timeleft -= tick;
if (timeleft < 1) setTimeout("runTimer()", tick + timeleft);
else setTimeout("runTimer()", tick);
}
}
}
</script>
And, it works when I place a PHP variable to load the time; but, I want to use it like the following:
when it reaches 0 seconds, I want it to update mySQL table and then come back to same page.
Is this possible? Thank you. This is my first time here.
I suggest you use a library such as jQuery, or a framework such as Backbone.js to make your life a little bit easier in handling javascript tasks.
To do what you want (if I'm understanding the question correctly), you would need something like the following. In the following example, I will assume you have jquery included in your webpage.
/*
* Your time-tracking code here
*/
// If the time left is 0 seconds/milliseconds/whatever
if(time_left === 0) {
// then do an AJAX request to the server page that handles updating the mysql table
$.ajax({
type: operation, // (GET, POSt, etc)
url: url, // The location of your php file relative to your root URL
data: {}, // the data you want the server (php file) to receive
success: function(data){
// Whatever you want to happen when the server succeeds with the operation
}
});
}
In your php file you would simply have a function that updates your table as you desire.
Hi every one i found it thank you, this is the answer to my question
when time reach 0 goes to this page then it returns to same page and repeats until no more time. coool. thank again
if (timeleft<=0)window.location.href="./mod.php";

How do I use setInterval with my form to create an alarm clock?

I'm currently trying to learn JavaScript and I've decided to make things more interesting by actually creating something instead of endless reading & no practice. I'm currently trying to build an alarm clock.
Here's my code:
http://codepen.io/anon/pen/dCsax
function wakeup() {
window.location = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
}
I need to create another function that uses setInterval to check every few seconds if the time set in that form is equal to the current time, and if it is, execute the wakeup function that plays Rick Astley - Never Gonna Give You Up.
I don't know how to write this piece of code. Could someone please help me out so I can see how it's done?
Thanks in advance.
For a pure JS solution (no libraries) you should read about Date object
I've forked your example on codepen like this:
function set_alarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
if ( t == 'PM' ) h+= 12;
var now = new Date();
var d = new Date();
d.setHours(h);
d.setMinutes(m);
d.setSeconds(0);
var delta = d.getTime() - now.getTime();
if (delta < 0) delta = -delta;
setTimeout(wakeup,delta);
}
This should give you a hint about what to do.
You can also try using one of the many libraries about dates, expecially moment.js
I added an id to your button, and on click set up the timer function as below:
<input id="scheduleTimer" type="button" value="Schedule alarm"></input>
function getTimeoutSec() {
var dt = new Date();
var currSecs = dt.getSeconds() + (60 * dt.getMinutes()) + (60 * 60 * dt.getHours());
var am_pm = document.getElementById('t').value;
var formHour = parseInt(document.getElementById('h').value);
if(am_pm == 'PM') {
formHour += 12;
}
var formMin = parseInt(document.getElementById('m').value);
var formSeconds = (formHour * 3600) + (formMin * 60);
return formSeconds - currSecs;
}
window.onload = function() {
var scheduleTimerButton = document.getElementById('scheduleTimer');
scheduleTimerButton.addEventListener('click', function() {
var secRemaining = getTimeoutSec();
setTimeout(wakeup, secRemaining * 1000);
}, false);
};
Link to CodePen
Here is an example function
function scheduleAlarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
alert("Successfully scheduled alram!");
setInterval(function(){
var date = new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
if (h == hours && m == minutes && t == ampm){
alert("Time to go to school, wake up!")
}
}, 5000); // will run every 5 seconds
}
Demo: CodePen

Use javascript to print out "Open" or Closed depending on time of day in real time

Ok, I have a website for a restaurant. Right now I have a simple if statement in javascript that changes a piece of text from Were open to Were Closed depending on the time of day. But If on a mobile phone when you close your browser it still technically is open in the background. So if you reopen the browser it will say were open after the time it should say were closed until you refresh the page. I would like to find a way to get it to update in real time. I have tried using setInterval and setTimeout to accomplish this as well as a while loop but so far, nothing. I mean when I use setInterval i can print the time and it will increment in real time. So why cant it run my if statement each second and print the desired piece of text.
Here is my code that just displays it as of now.
var date = new Date().getHours();
if ((date > 9) && (date < 20) && (day != 0)) {
y="<span style=\"color:#07ed11\">We're Open!</span>";
}
else {
y="<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML=y;
I just want it to print our in real time so that I can watch it change from open to close once the time hits it right
jsFiddle example
New version
I took the liberty of going back and revising this. I think this version will work better
var checkOpenStatus = function () {
var d = new Date();
var date = d.getHours();
var day = d.getDay();
if ((date > 9) && (date < 20) && (day != 0)) {
y = "<span style=\"color:#07ed11\">We're Open!</span>";
} else {
y = "<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML = y;
setTimeout(checkOpenStatus,15000);
};
checkOpenStatus();
It runs every 15 seconds rather than every 100 milliseconds.
Old Version
Try this
var checkOpenStatus = function () {
var d = new Date();
var date = d.getHours();
var day = d.getDay();
if ((date > 9) && (date < 20) && (day != 0)) {
y = "<span style=\"color:#07ed11\">We're Open!</span>";
} else {
y = "<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML = y;
}
setInterval(checkOpenStatus,100); //removed anon function
It updates every 100 milliseconds on the setInterval. You can change it to be faster or slower according to your preference.
var checkOpenStatus =function () {
var d = new Date();
var date = d.getHours();
var min = d.getMinutes();
if ((date>7 || (date == 7 && min >= 30)) && (date < 22) && (day != 0)) {
y = "<span style=\"color:#07ed11\">We're Open!</span>";
} else {
y = "<span style=\"color:#fc4b1c\">Sorry we're Closed.</span>";
}
document.getElementById("open-close").innerHTML = y;
};
checkOpenStatus();
Less intrusive closure style:
var updateElement = function($el) {
return function updater() {
$el.text(new Date()); // dummy, your logic goes here...
setTimeout(updater, 100);
}
}
var fooUpdater = updateElement($("#foo"));
setTimeout(fooUpdater,1000)

Categories