I am trying to get the contents of a dynamically generated Iframe (same-domain). I have this so far.
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().attr('title');
var getTime = setInterval(function() {
var newTime = $('.date-and-time , frame.contents()').last().attr('title');
},500);
I tried lines 1 and 2 together with an alert of time to see if I was actually grabbing the data. Though I am not. Basically what I want to do is get the last message .data-and-time and with the setInterval get the same thing.
If they are different do something.
This is how I believe my code will be set up once i get the data
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().attr('title');
var getTime = setInterval(function() {
var newTime = $('.date-and-time , frame.contents()').last().attr('title');
},500);
if(time === newTime) {
alert();
}
Any suggestions on grabbing data from iframe?
Also tried=
var frame = $('#avacweb_chat iframe');
var time = $(frame).contents($('.date-and-time'));
alert(time.length);
Which I get 1 which is correct
Then I tried
var frame = $('#avacweb_chat iframe');
var time = $(frame).contents($('.date-and-time').attr('title'));
alert(time);
Which becomes [object Object]
Working code =
var frame = $('#avacweb_chat iframe');
var time = $('.date-and-time' , frame.contents()).last().attr('title');
var newTime = setInterval(function() {
var newT = $('.date-and-time' , frame.contents()).last().attr('title');
},500);
if(time !== newT) {
alert('New Message');
}
Now my question would be how do I get the newTime store it and then compare them?
Maybe it's a race condition. Would it be possible that your iFrame hasn't completely loaded at the time you're trying to traverse the DOM? Give this a shot:
var frame = $('#avacweb_chat iframe'),
newTime;
frame.on('load', function(){
newTime = frame.contents().find('.date-and-time').attr('title');
});
alert(newTime);
Related
I have this script for to increment a counter by one after 1 second , but when I refresh the page I need to remember the last number I counted.
Example: Currently, I have 40. When I refresh the page I need to start counting after 40 not reset to 1. Is this possible?
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(obj.innerHTML);
setInterval(function() {
current++;
// Update the contents of the element
obj.innerHTML = current;
}, 1000);
}
animateValue('value');
<h1>
<div id="value">1</div>
</h1>
You can store the counter progress in localStorage, then retrieve the value on page load and start counting from there:
var obj = document.getElementById("value");
let counterStorage = localStorage.getItem('counter')
if(counterStorage) obj.innerHTML = counterStorage
function animateValue(id) {
var current = parseInt(obj.innerHTML);
setInterval(function() {
current++;
localStorage.setItem('counter', current)
obj.innerHTML = current;
}, 1000);
}
animateValue('value');
Use localstorage. If not exists then set and if exists use the value from localstorage.
function animateValue(id){
const obj = document.getElementById(id);
let current = parseInt(obj.innerHTML);
const storageTime = localStorage.getItem("mytime")
if ( storageTime === null) {
localStorage.setItem("mytime", current);
} else {
current = storageTime;
}
setInterval(function(){
current++;
localStorage.setItem("mytime", current);
// Update the contents of the element
obj.innerHTML = current;
},1000);
}
animateValue('value');
<h1><div id="value">1</div></h1>
you can use window.localstorage. the code will look something like this
window.localstorage.setItem('timer', timer)
Problem is my timer was working as well. But when i save timers value to localStorage. I just want to when user refresh timer wont stop and resume when stopped at.
javascript
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){ document.myform.submit(); }
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
var startTime = document.getElementById("timer").value;
localStorage.setItem("startTime", startTime);
//alert(startTime);
}
function Dahin(){
var startTime = localStorage.getItem("startTime");
document.getElementById('timer').value = startTime;
}
in my view
<h3 onload="Dahin();" class="page-title">Шалгалтын 50 асуулт</h3><h4><div>Үлдсэн хугацаа = <span id="timer">{{ $time }}</span></div></h4>
Update fixed timer
now how to save timer value to sessionstorage and retrieve when refresh page
Let change your code:
var check = localStorage.getItem("startTime");
var startTime = check ? check : document.getElementById("timer").innerHTML;
document.getElementById('timer').value = startTime;
function Dahin(){
localStorage.setItem("startTime", startTime);
}
the problem why you get null is because you use .value. You put your time into span tag. .value is only work for input field
I have an issue that hold my neck with time interval. I am calculating my time/clock one second at a time with the function below.
Header.prototype= {
time_changed : function(time){
var that = this;
var clock_handle;
var clock = $('#gmtclock');
that.time_now = time;
var increase_time_by = function(interval) {
that.time_now += interval;
};
var update_time = function() {
clock.html(moment(that.time_now).utc().format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time();
clearInterval(clock_handle);
clock_handle = setInterval(function() {
increase_time_by(1000);
update_time();
}, 1000);
},
};
The above works fine and increase my time a second at a time correctly . However. I added another event that fires on web changed or tab navigated.
var start_time;
var tabChanged = function() {
if(clock_started === true){
if (document.hidden || document.webkitHidden) {
start_time = moment().valueOf();
time_now = page.header.time_now;
}else {
var tnow = (time_now + (moment().valueOf() - start_time));
page.header.time_changed(tnow);
}
}
};
if (typeof document.webkitHidden !== 'undefined') {
if (document.addEventListener) {
document.addEventListener("webkitvisibilitychange", tabChanged);
}
}
The above fires when ever user leave the page and comes back . It add the delay to the time. However, i notice the second increase rapidly . and very past my timer does not fire very second any more as specified in the clock hand. It add second every milliseconds and fats. Please why this and how do i fix this ? My time run fast and ahead when ever i change tab and returned . Any help would be appreciated
Update
Below is my WS request function.
Header.prototype = {
start_clock_ws : function(){
var that = this;
function init(){
clock_started = true;
WS.send({ "time": 1,"passthrough":{"client_time" : moment().valueOf()}});
}
that.run = function(){
setInterval(init, 900000);
};
init();
that.run();
return;
},
time_counter : function(response){
var that = this;
var clock_handle;
var clock = $('#gmt-clock');
var start_timestamp = response.time;
var pass = response.echo_req.passthrough.client_time;
that.time_now = ((start_timestamp * 1000) + (moment().valueOf() - pass));
var increase_time = function() {
that.time_now += (moment().valueOf() - that.time_now);
};
var update_time = function() {
clock.html(moment(that.time_now).utc().format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time();
clearInterval(clock_handle);
clock_handle = setInterval(function() {
increase_time();
update_time();
}, 500);
},
};
and in my WS open event
if(isReady()=== true){
if (clock_started === false) {
page.header.start_clock_ws();
}
}
In my WS onmessage event
if(type ==='time'){
page.header.time_counter(response);
}
Base on your suggestion, i modified my increase_time_by to
var increase_time_by = function() {
that.time_now += (moment().valueOf() - that.time_now);
};
It seems fine now. Would test further and see.
Instead of incrementing the clock by the value of the interval, just update the clock to the current time with each pass. Then it won't matter if you fire exactly 1000 ms apart or not.
You actually may want to run more frequently, such as every 500 ms, to give a smoother feel to the clock ticking.
Basically, it comes down to the precision of the timer functions, or lack thereof. Lots of questions on StackOverflow about that - such as this one.
Based on your comments, I believe you are trying to display a ticking clock of UTC time, based on a starting value coming from a web service. That would be something like this:
var time_from_ws = // ... however you want to retrieve it
var delta = moment().diff(time_from_ws); // the difference between server and client time
// define a function to update the clock
var update_time = function() {
clock.html(moment.utc().subtract(delta).format("YYYY-MM-DD HH:mm") + " GMT");
};
update_time(); // set it the first time
setInterval(update_time, 500); // get the clock ticking
We have some problem with our image animation with speed control.
It make use of a timeout to change the image, but we want to change the timeout value with a slider, but for some sort of reason, it doesn't work. Can someone help us out ?
We have a Jfiddle here: http://jsfiddle.net/Kbroeren/fmd4xbew/
Thanks! Kevin
var jArray = ["http://www.parijsalacarte.nl/images/mickey-mouse.jpg", "http://www.startpagina.nl/athene/dochters/cliparts-disney/images/donad%20duck-106.jpg", "http://images2.proud2bme.nl/hsfile_203909.jpg"];
var image_count = 0;
function rollover(image_id, millisecs) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
rollover("img1", 200);
$(function () {
var value;
var $document = $(document),
$inputRange = $('input[type="range"]');
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value,
output = element.parentNode.getElementsByTagName('output')[0];
output.innerHTML = value;
}
for (var i = $inputRange.length - 1; i >= 0; i--) {
valueOutput($inputRange[i]);
};
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
rollover("img1", 200);
});
// end
$inputRange.rangeslider({
polyfill: false
});
});
You keep creating more and more infinite function calls without stopping them.
After you call your function the first time, it keeps calling itself.
then you call it again with different interval (millisecs) and it will also start call itself....
You can try two different approach.
1.Use setInterval instead of setTimeout. Use clearInterval to clear the interval before setting it with a new value.
/// Call animation() every 200 ms
var timer = setInterval("Animation()",200);
function ChageSpeed(miliseces){
///Stop calling Animation()
clearInterval(timer);
/// Start calling Animation() every "miliseces" ms
timer = setInterval("Animation()",miliseces);
}
function Animation(){
/// Animation code goes here
}
2.Or, Instead, Set your interval as a global variable (not cool) and just change it value when the user want to change the animation speed.
var millisecs = 200;
function rollover(image_id) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
millisecs = YourNewValue;
});
I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});