Javascript breaks getting timezone without DST - javascript

I'm trying to set a user's timezone offset for PHP, being sent over ajax. A page has been loaded with session data. If there is no data this gets put into the page:
<script type="text/javascript">
$(document).ready(function() {
var visitortime = new Date();
visitortime.setMonth(1);
var visitortimezone = visitortime.getTimezoneOffset()*60;
$.ajax({
url: "/ajax/timezone/set/"+ visitortimezone,
success: function(){
location.reload();
}
});
});
</script>
without the visitortime.setMonth(1); it runs fine and returns the right offset. But with it, it returns only 0.
I want to be able to get timezone offset without DST and then run DST check on the PHP side.

I managed to fix it with this bit of code:
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
$(document).ready(function() {
var visitortime = new Date();
var visitortimezone = visitortime.getTimezoneOffset()*60;
if(visitortime.dst()){
visitortimezone = visitortimezone + 60*60;
}
$.ajax({
type: "GET",
url: "/ajax/timezone/set/"+ visitortimezone,
success: function(){
location.reload();
}
});
});
Found here: Check if Daylight Saving Time is in effect, and if it is for how many hours.

Related

Pass javascript variable data to MySQL database in this situation

I have followed a codepen project to build an animated form. May I know how can I store the answer to my SQL database? The answers are stored in the questions array with the key answer but I am not sure how to extract them. Thanks!
var questions = [
{question:"What's your first name?"},
{question:"What's your last name?"},
{question:"What's your email?", pattern: /^[^\s#]+#[^\s#]+\.[^\s#]+$/},
{question:"Create your password", type: "password"}
]
var onComplete = function() {
var h1 = document.createElement('h1')
h1.appendChild(document.createTextNode('Thanks ' + questions[0].answer + ' for checking this pen out!'))
setTimeout(function() {
register.parentElement.appendChild(h1)
setTimeout(function() { h1.style.opacity = 1 }, 50)
}, 1000)
}
;(function(questions, onComplete) {
var tTime = 100 // transition transform time from #register in ms
var wTime = 200 // transition width time from #register in ms
var eTime = 1000 // transition width time from inputLabel in ms
if (questions.length == 0) return
var position = 0
putQuestion()
forwardButton.addEventListener('click', validate)
inputField.addEventListener('keyup', function(e) {
transform(0, 0) // ie hack to redraw
if (e.keyCode == 13) validate()
})
previousButton.addEventListener('click', function(e) {
if (position === 0) return
position -= 1
hideCurrent(putQuestion)
})
function putQuestion() {
inputLabel.innerHTML = questions[position].question
inputField.type = questions[position].type || 'text'
inputField.value = questions[position].answer || ''
inputField.focus()
progress.style.width = position * 100 / questions.length + '%'
previousButton.className = position ? 'ion-android-arrow-back' : 'ion-person'
showCurrent()
}
}(questions, onComplete))
In order for it to work you need jquery support for your website
Try doing following:
Assume you are storing your variables in JS array like
var numbers = [45, 4, 9, 16, 25];
You can try using built-in JS funtion to cycle through the array like:
numbers.forEach(myFunction);
You define your function that you use in point 2, with ajax, smth like
myFunction(value){
// answers is used to indicate to your server side script type of operation to be performed to be use in isset(), as value is too general`
var datastring = 'answers' + '&value=' + value;
// in URL indicate path to your actual server side script that will put records in database
ajax({
type: "POST",
url: "/app/server.php",
data: datastring,
success: function (html) {
console.log(html);
}
}); //End of Ajax
return false;
}

Javascript - Favorite button that saves a cookie and remains saved when user refreshes the page?

I'm trying to create a favorite button for my sample site for class. When I click the button it works and takes the user to the detail page as needed but when I go back to the main page it doesn't update/save the image as a favorite. I've tried to figure it out but I'm a bit new to coding so I'm struggling a bit.
I've tried switching around the format and referring to online references. I played around a bit with ajax but still wasn't able to get it to save.
Javascript:
function myFunction(elem) {
var i = document.getElementById(elem.id);
if(elem.id <= ids.length) {
i.addEventListener("click", function() {
var name = getCookie("imgNum");
setCookie("imgNum", name, 30);
});
}
var a = document.createElement("BUTTON");
a.innerHTML = "faved";
i.parentNode.replaceChild(a, i);
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var iUrl = imgUrl[cname];
return imgUrl;
}
function checkCookie() {
var name = getCookie("imgNum");
setCookie("imgNum", name, 30);
}
function myFunctionTwo(elem) {
var y = document.getElementById(elem.id);
}

momentJS Timer doesn´t work on Firefox

I implemented a countdown timer via Moment.js library, and unfortunately it doesn't work on Firefox.
This is my code:
function createTimer(begin, timeUp) {
var timer = document.getElementById('timer');
var timerDays = document.getElementById('days').children[0];
var timerHours = document.getElementById('hours').children[0];
var timerMinutes = document.getElementById('minutes').children[0];
var timerSeconds = document.getElementById('seconds').children[0];
var intervalID = window.setInterval(function () {
// Difference between timeUp and now
var differenceToTimeUp = moment.duration(timeUp.diff(moment()));
// Difference between begin and now
var differenceToBegin = moment.duration(begin.diff(moment()));
if (differenceToTimeUp.asSeconds() > 0) {
timer.classList.remove('hidden');
} else {
timer.classList.add('hidden');
}
timerDays.innerText = ('0' + differenceToTimeUp.days()).slice(-2);
timerHours.innerText = ('0' + differenceToTimeUp.hours()).slice(-2);
timerMinutes.innerText = ('0' + differenceToTimeUp.minutes()).slice(-2);
timerSeconds.innerText = ('0' + differenceToTimeUp.seconds()).slice(-2);
}, 1000);
}
document.addEventListener('DOMContentLoaded', function () {
// // Comment out for production
// var test1 = moment('2016-02-02 11:00:00');
// var test2 = moment('2016-03-11 11:00:00');
// createTimer(test1, test2);
var now = moment(new Date(moment())).utc().format("YYYY-MM-DD HH:mm:ss");
var firstStart = moment('2016-02-11 11:00:00');
var firstEnd = moment('2016-02-15 17:00:00');
var secondStart = moment('2016-02-16 14:00:00');
var secondEnd = moment('2016-02-17 17:00:00');
if (now > firstStart._i && now < firstEnd._i) {
createTimer(firstStart, firstEnd);
}
});
In debugger I can see that moment is getting the date, so I think it has something to do with the setInterval function.
Any ideas?
UPDATE
Got it working. The mistake was actually not with momentJS. Changing the Text element with .innerText didn´t work on InternetExplorer. Using .textContent fixed it. I hade issues with my custom fonts as well on InternetExplorer when i used .tff. Using .woff worked fine.

Why wouldn't this countdown timer show on my mobile?

I have some Javascript that is basically a countdown timer:
<script>
var clockRunning = false;
var clockPlaceholder = document.getElementById("clock-placeholder");
var targetDate;
var clock;
function updateClock() {
var cd = countdown(targetDate, null, countdown.DAYS | countdown.HOURS | countdown.MINUTES | countdown.SECONDS, 4);
clockPlaceholder.innerHTML = cd.toString();
if (targetDate.getTime() < (new Date()).getTime()) {
endCountdown();
}
}
function startCountdown() {
if (clockRunning == false) {
var h, m, s;
// setup target Date object
var now = new Date(); // console.debug(now.toString());
var laravelTime = '{{ $auction->endtime }}';
targetDate = new Date(laravelTime);
// start clock
clock = setInterval(updateClock, 1000);
clockRunning = true;
}
}
function endCountdown() {
clockPlaceholder.innerHTML = "Auction Ended"
clearInterval(clock);
clockRunning = false;
}
</script>
This line: var laravelTime = '{{ $auction->endtime }}'; just gets the endtime from the DB.
Anyway, it works perfectly on my computer but when I browse to the page on my mobile phone (iOS) it doesn't appear at all. Neither Safari nor Chrome shows it.
I'm quite new to js. Any help would be appreciated!

Restart jQuery Countdown

Hello I'm currently working on a jQuery plugin.
http://plugins.jquery.com/kbw.countdown/
I want to restart the counter when it reaches 00:00:00 time.
<script type="text/javascript">
$(function () {
var austDay = new Date();
austDay = new Date(austDay.getFullYear() + 1, 1 - 1, 00);
$('#defaultCountdown').countdown({until: '+5s'});
$('#year').text(austDay.getFullYear());
});
</script>
You can set your target times and initialize with an expiry event like this:
$('#noon-countdown').countdown({until: getNoonCountDown(),
serverSync: serverTime, format: 'HMS',
onExpiry: function() {
$(this).countdown('change', {until: getNoonCountDown()});
}});
$('#midnight-countdown').countdown({until: getMidnightCountDown(),
serverSync: serverTime, format: 'HMS',
onExpiry: function() {
$(this).countdown('change', {until: getMidnightCountDown()});
}});
function getNoonCountDown() {
var until = new Date();
until.setHours(until.getHours() < 12 ? 12 : 36, 0, 0, 0); // Next midday
return until;
}
function getMidnightCountDown() {
var until = new Date();
until.setHours(24, 0, 0, 0); // Next midnight
return until;
}

Categories

Resources