So, my countdown script is for some reason not compatible with my code.
Im trying to make it countdown to a specific time each day, but my web store is limited to only use jquery 1.x with all my other plugins so no other jquery version can be used.
https://jsfiddle.net/nskhbL12/
<script>
window.onload = date;
function ShowTime() {
var now = new Date();
var hrs = 20-now.getHours();
var mins = 60-now.getMinutes();
var secs = 60-now.getSeconds();
timeLeft = "" +hrs+' t : '+mins+' m : '+secs+' s';
$("#countdown").html(timeLeft);
}
var countdown;
function StopTime() {
clearInterval(countdown);
}
setInterval(ShowTime ,1000);
</script>
<span id="date">Order before <span id="countdown"></span> and receive your package tomorrow!</span>
Try with
jQuery(function($) {
setInterval(ShowTime ,1000);
});
Or use something like
$ = jQuery;
Related
I wrote the following code and didn't want to repeat the function (today) twice so I tried writing it within the callback function afterAdd but it didn't work. Why can't it be detected by the callback function?
<script type="text/javascript">
var today = $(document).ready( function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
});
$(".addform .repeatable").repeatable({
addTrigger: ".add",
deleteTrigger: ".del",
template: "#form_item",
afterAdd: today
});
</script>
First create today as a function. Then call $(document).ready(today), and also use today in your code as per normal:
var today = function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0, 10));
};
$(document).ready(today);
$(".addform .repeatable").repeatable({
addTrigger: ".add",
deleteTrigger: ".del",
template: "#form_item",
afterAdd: today
});
Replace
var today = $(document).ready( function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() -
todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
});
with
var today = function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() -
todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
};
$(document).ready(function() {
today();
});
This will create the function 'today' and run it when the document is ready.
<div class="wait">Wait</div>
<div class="waitDownloadLink"></div>
$(document).ready(function()
{
var secondNormal = 40;
var refreshIntervalId;
refreshIntervalId = setInterval(function() {
secondNormal -= 1;
$(".wait").text(secondNormal);
}, 1000);
setTimeout(function() {
clearInterval(refreshIntervalId);
$(".waitDownloadLink").text("Click me to download");
}, secondNormal * 1000);
});
When I start running the code and stay on the webpage, the code seems too work perfectly (or nearly). However, when I surf on other webpage right after I started the code, the timer is stuck between 12 - 18 second and then stops running. Why does this happen? And is there any solution to solve this?
https://jsfiddle.net/s1zf18co/
Browsers typically pause or reduce thread priority for Javascript running in tabs that aren't visible. My guess is that it's a power saving measure for laptops and other things, but they all have done this for years now. This question has an incredibly thorough investigation into the issue.
The solution is to use web workers which don't get paused. See the Mozilla documentation for more information.
I cannot seem to replicate the bug, however I believe that using the Date object may fix it:
var getDateTimeInSeconds = function() {
return Math.floor(Date.now() / 1000)
};
$(document).ready(function() {
var numOfSeconds = 40;
var countFrom = getDateTimeInSeconds();
var countTo = countFrom + numOfSeconds;
var refreshIntervalId = setInterval(function() {
var secondsLeft = countTo - getDateTimeInSeconds();
if (secondsLeft < 0) {
$(".wait").text(0);
$(".waitDownloadLink").text("Click me to download");
clearInterval(refreshIntervalId);
} else {
$(".wait").text(secondsLeft);
}
}, 1000);
});
Fiddle: https://jsfiddle.net/s1zf18co/1/
there is one working solution, try this and c if it is good enough, it is ok with leaving page problem, edit on end condition.
$(document).ready(function () {
var secondNormal = 40;
var refreshIntervalId = setInterval(function () {
setTimeout(function () {
if(secondNormal >0) {
secondNormal -= 1;
}
}, 1000)
$(".wait").text(secondNormal);
}, 1000);
});
Aside from Mordred's answer, in this case you may try using JS Date object to correctly estimate time. Check out this question.
I created ajax to get start time and end time from another page and setInterval for this function every second like this.
setInterval(function () {
CheckTime()
}, 1000);
function CheckTime() {
$.ajax({
url: "Get_TIme.php",
success: function (result) {
var time = result.split('|');
var start_time = time[0];
var end_time = time[1];
var getTime = new Date();
var currentHours = getTime.getHours();
var currentMinutes = getTime.getMinutes();
var currentTime = currentHours + ":" + currentMinutes;
if ((currentTime == start_time) || (currentTime == end_time)) {
$('#first').load('demo.php #first'); //reload div
}
}
});
At first time when current time = start time, <div> can refresh itself. But when current time = end time, <div> doesn't reload itself. I don't what happen on this code. But I replace alert before if((currentTime==start_time)||(currentTime==end_time)) like this:
alert("something");
if((currentTime==start_time)||(currentTime==end_time))
{
$('#first').load('demo.php #first'); //reload div
}
<div> can reload itself when current time = end time. Anyone can suggest me what happen on my code.
I think load must be use like that :
$('#first').load('demo.php');
this is what I saw in the documentation here
Try this:
if((currentTime==start_time)||(currentTime==end_time))
{
$('#first').load('demo.php'); //reload div
}
if you want show #first use following;
$(document).ready(function(){
$("#first").css("class","active");
}
just need a little help here. My problem is, how can I count the seconds when i hover a specific element. Like for example when I hover a button, how can i count the seconds did i stayed in that button after I mouseout?
An alternate solution using setInterval. DEMO HERE
var counter = 0;
var myInterval =null;
$(document).ready(function(){
$("div").hover(function(e){
counter = 0;
myInterval = setInterval(function () {
++counter;
}, 1000);
},function(e){
clearInterval(myInterval);
alert(counter);
});
});
A simple example
var timer;
// Bind the mouseover and mouseleave events
$('button').on({
mouseover: function() {
// set the variable to the current time
timer = Date.now();
},
mouseleave: function() {
// get the difference
timer = Date.now() - timer;
console.log( parseFloat(timer/1000) + " seconds");
timer = null;
}
});
Check Fiddle
How about this quick plugin I just knocked out, which will work on multiple elements, and without using any global variables:
(function($) {
$.fn.hoverTimer = function() {
return this.on({
'mouseenter.timer': function(ev) {
$(this).data('enter', ev.timeStamp);
},
'mouseleave.timer': function(ev) {
var enter = $(this).data('enter');
if (enter) {
console.log(this, ev.timeStamp - enter);
}
}
});
};
})(jQuery);
Actually disabling the functionality is left as an exercise for the reader ;-)
Demo at http://jsfiddle.net/alnitak/r9XkX/
IMHO, anything using a timer for this is a poor implementation. It's perfectly trivial to record the time without needing to use an (inaccurate) timer event to "count" seconds. Heck, the event object even has the current time in it, as used above.
This is exam:
var begin = 0;
var end = 0;
$('#btn').hover(function () {
begin = new Date().getTime();
});
$('#btn').leave(function () {
end = new Date().getTime();
sec = (end - begin) / 1000;
alert(sec);
});
One way to go about it would be the event.timeStamp method :
var initial_hover, exit_hover;
$('#ele').hover(
function(event){
initial_hover = event.timeStamp
console.log(initial_hover);
},
function(event){
exit_hover = event.timeStamp
$(this).html(exit_hover - initial_hover);
console.log(exit_hover);
}
);
jsfiddle
You've tagged the question with JQuery, so here's a jQuery solution.
$(element).on('mouseover', function(e){
$(e.target).data('hover-start', new Date().getTime());
});
$(element).on('mouseout', function(e){
// count the difference
var difference = new Date().getTime() - $(e.target).data('hover-start');
// clean up the data
$(e.target).data('hover-start', undefined);
console.log('Mouse was over for', difference/1000, 'seconds');
});
use setInterval and store value in variable. call the function on mouserover.
function mouseover(){
var start = 0;
setInterval(function(){
start++;
var count = start;
}, 1000);
}
This may not be the place for this question, but here goes anyways.
I am trying to learn more about the JS timers and am using the JS Fiddle for this purpose. In my script, I am using a script that binds functionality to a few elements, but I need the JS Fiddle to not execute it until the page loads completely due to it needing all elements to be initialized and available (see my fiddle at: http://jsfiddle.net/radi8/W2b2M/4/). This fiddle is a VERY rough skeleton.
The format of the script is as follows:
How can I make the JS Fiddle only load this after all other elements are finished?
$(document).ready(function() {
var tmr = {
init: function(){
},
somefunct1: function(){
},
somefunction2: function(){
}
};tmr.init();
});
Any help is appreciated.
document.ready() is the way to good. However, there are other issues with your code. This function is not defined correctly:
function stopTimer {
clearInterval(timer);
}
Should be:
function stopTimer() {
clearInterval(timer);
}
Also, startstop.value is not defined. What is startstop suppose to be?
Update
Your use of .val() is incorrect, and many other issues (fixed):
http://jsfiddle.net/W2b2M/17/
Check this Fiddle:
A simple Javascript Function to Set timer.
$(document).ready(function () {
var input = 120;
function calculateTime(timer) {
var timer = timer;
var mins = Math.floor(timer / 60);
var secs = timer % 60;
var time = (mins < 10 ? "0" : "") + mins + ":" + (secs < 10 ? "0" : "") + secs;
return time;
};
setInterval(function () {
data = calculateTime(input)
if (input > 0)
{
$("#timer").text(data);
input--;
}
else
{
$("#timer").text("Time Out, Njoy Coding in JavaScript")
}
}, 1000);
});
http://jsfiddle.net/MUMU1987/sUkjj/