Can I use javascript timer in a mobile browser - javascript

I am using IE in a mobile browser. I add a javascript function to a button that when the User clicks it says 'hello'.
This works.
I then add a timer.
On a desktop browser it works.
it does not work on my mobile browser.
This is my code. (note I Had just tried placing an alert('hi'); in the swapImages() and that did not work either.
var div = document.getElementById('divImage');
var imgCached = document.getElementById('imgCached');
document.execCommand("BackgroundImageCache", false, true);
function OnImgLoaded() {
img1.src = imgCached.src;
}
var interval = 30;
var _timer;
var _index = 0;
function test() {
_timer = setInterval('swapImages()', interval);
}
function swapImages() {
imgCached.onload = OnImgLoaded();
imgCached.src = 'my server url~/' + '0000' + _index + '.jpg';
_index = _index + 1;
if (_index == 10) {
_index = 0;
clearTimeout(_timer);
}
}
UPDATE!!
I had been runningit on Chrome desktop and not IE. I am mow testing it in IE desktop. I get the same erro so now I can debug.
The error is this line:
img1.src = imgCached.src;
It tells me:
Unable to get property 'src' of undefined or null reference
I have changed the code to:
var imgLive = document.getElementById('imgLive'); (I have renamed the img control)
function OnImgLoaded() {
imgLive.src = imgCached.src;
}
I get the same error.
I look in Source and the control is correctly named..
Thanks

i'm not sure that the following line is valid in your mobile phone:
imgCached.src = 'http://127.0.0.1/Cloud/test/' ...
the timer executes successfully, but the image doesn't get the proper src since the device doesn't run a web server on it (unless you configured one).
and to answer your topic question, yes- you can use javascript timers in mobile browsers just like desktop browsers.
hope that helped.

First of all: Do you ever call the test function, that starts the timer?
Second: Maybe it's really document.execCommand("BackgroundImageCache", false, true), that fails - it may not be enabled in the mobile version of IE that you are using. You can check if it's enabled using the queryCommandEnabled function, see more here: http://msdn.microsoft.com/en-us/library/ie/ms536676(v=vs.85).aspx

Related

How is it possible, that ajaxing is much more slower in Chrome and IE than Mozilla?

I would like to ask you to find the point, why the site -I'm working on- is slow.
the conditions of the problem:
large row count (so I think maybe the problem is related to this.)
there is ajaxing event (I have tired to comment it out and the problem disappeared)
using not Mozilla (this freeze effect appear in IE and Chrome)
description of the problem (see the image):
I change the value of input
after there is an ajax call (in order to calculate prize) and it takes in FF about 30 ms otherwise more than 1 s
there is a freeze until the ajax finished (but ajax is not set to async:false)
only after that can I change the next input
I have tired to reproduce the error, but I could't. So see the original site:
site: foto/fotokidolgozas/elohivas-beallitasok.php
Log in and pass: d838292#rtrtr.com
Update: It works now fine, the trick is the following:
I use hidden input fields, their values are json_encode-d strings. I can process them anytime with js.
Thank you for any help!
Code:
$('#cikkek,#magic_bar').on("change","select,textarea,input[type!=hidden]",function(event_object){
if( $(this).attr('name') == "kijelolve" && !$(this).parents('#magic_bar').length)return true;
var cikk_id = $(this).parents('.cikk').attr('id');
var cikk_tipus = $("input[name=cikk_tipus]").val();
var tulajdonsag = $(this).attr('name');
var ertek = $(this).val();
if(ertek == "-1")return false;
if($(this).is('[type=checkbox]'))ertek = $(this).prop("checked")?'1':'0';
if(cikk_tipus=='fotokidolgozas' && (tulajdonsag=='meret'||tulajdonsag=='vagas'))
{
var sor = $(event_object.target).parents('.cikk');
var act_meret = sor.find('select[name=meret]').val();
var act_fill = sor.find('select[name=vagas]').val();
var act_zold_class = sor.find("input[name=zold_"+act_meret+"]").val()=="1" ?"zold":"feher" ;
var name = "src_"+act_meret+"_"+act_fill;
var name2 = "szoveges_uzenet_"+act_meret+"_"+act_fill;
sor.find(".img_cont").find("img").attr("src",sor.find("input[name="+name+"]").val());
sor.find(".szoveges_uzenet").text(sor.find("input[name="+name2+"]").val());
sor.find(".dpi_megfelel").text(sor.find("input[name=minoseg_"+act_meret+"]").val()+" ("+sor.find("input[name=dpi_"+act_meret+"]").val()+" dpi)");
sor.find("select[name=meret]").removeClass("feher zold").addClass(act_zold_class);
}
var before = now();
//this is the ajax part
if(ajax_modositaskor)
$.post('/_fn/cikk/mod.php',{
'cikk_tipus':cikk_tipus,
'cikk_id':cikk_id,
'tulajdonsag':tulajdonsag,
'ertek':ertek
},function(a){
var elapsed = now() - before;
if(a[0]!="1")
{
//error
alert(a[0]);
return;
}
if(a[1]!="-1")
{
//there is new price
$(event_object.target).parents('.cikk').find('.ar').text(a[1]);
}
if(a[2]!="-1")$('#cikkek_ara').text(a[2]);
osszegzest_frissit(a[3]);
var php_time = Math.round(a[4])
a_min = Math.min(a_min,elapsed);
p_min = Math.min(p_min,parseFloat(php_time));
a_max = Math.max(a_max,elapsed);
p_max = Math.max(p_max,parseFloat(php_time));
if(!a_avg)a_avg = elapsed;else a_avg= Math.round((a_avg+elapsed)/2);
if(!p_avg)p_avg = php_time;else p_avg = Math.round((p_avg+php_time)/2);
trace("ajax="+elapsed+"\tphp="+php_time+"\tajax_min="+a_min+"\tphp_min="+p_min+"\tajax_max="+a_max+" \tphp_max="+p_max+"\tajax_avg="+a_avg+" \tphp_avg="+p_avg);
},"json").error(function() { postHiba() });
});
The problem was that the hidden data was too large (see my other question), and it decreased the processing time. (Firefox seems to be well coded, because this does not mattered)
Now the problem is fixed.

Correct access of dynamic iFrame in IE

Plain JS - please no jQuery suggestions - it is for a bookmarklet that needs to use as plain JS as possible.
I hope someone KNOWS the answer since I cannot reliable create a fiddle.
This code will run in the scope of the page it is inserted in - it works perfectly in Fx6-9, safari and latest Chromes on Windows XP and OSX - Only IE gives me undefined when I try to access the iFrame
var zContainer = document.getElementById('zContainer');
if (zContainer==null) {
zContainer = document.createElement("div");
zContainer.id="zContainer";
document.body.appendChild(zContainer);
}
var zStuff = {}; // minimise window var footprint
zStuff.html = '<body>Hello</body>';
if (!zFrame) { // did we already have one?
zFrame = document.createElement("iframe");
zFrame.id="zIframeId"; zFrame.name="zIframeName"; zFrame.frameBorder="0";
zIFS = zFrame.style; zIFS.border="0"; zIFS.width="500px"; zIFS.height="500px"; zIFS.backgroundColor="white"; zIFS.display="block";
zContainer.appendChild(zFrame); // append to div
zFrame = window.frames["zIframeName"]; // undefined in IE8 !!!!!
// zFrame = document.getElementById("zIframeId"); // undefined in IE8 !!!!!
zFrame.src="javascript:'<body></body>'"; // initialise body
zFrame.document.write(zStuff.html); // or zFrame.contentDocument.write
zFrame.document.close();
// zFrame.document.body.innerHTML=zStuff.html; // also does not work
// zFrame.src="javascript:'"+zStuff.html+"'"; // alternative method - either one works in Fx/Chrome
}
Thanks for any hints and for not voting this down. I hope the SO community will be as
helpful to me as I have been to it over the last year and a half...
Update - since the code I posted had some remnants of desperation, I changed it to
if (!zFrame) { // did we already have one?
zFrame = document.createElement("iframe");
zFrame.id="zIframeId"; zFrame.name="zIframeName"; zFrame.frameBorder="0";
zIFS = zFrame.style; zIFS.border="0"; zIFS.width="500px"; zIFS.height="500px"; zIFS.backgroundColor="white"; zIFS.display="block";
zContainer.appendChild(zFrame); // append to div
zFrame.src="javascript:'<body></body>'"; // initialise body
zFrame.document.write(zStuff.html); // or zFrame.contentDocument.write
zFrame.document.close();
}
the above now replaces the page I am on with the code in the zStuff.html
instead of replacing only the iFrame content - it also broke in Fx
Now I have to do this in Fx which IE also does not mind but still replaces the window and not the iFrame
if (!zFrame) {
zFrame = document.createElement("iframe");
zFrame.scrolling="no"; zFrame.id="zIframeId"; zFrame.name="zIframeName"; zFrame.frameBorder="0";
zIFS = zFrame.style; zIFS.border="0px none"; zIFS.width="549px"; zIFS.height="510px"; zIFS.backgroundColor="white"; zIFS.display="block";
zDRContainer.appendChild(zFrame);
zFrame.src="javascript:'<body></body>'";
setTimeout(function() {
var zFrame = window.frames["zIframeName"]; // this is needed for the document.write
zFrame.document.write(zStuff.html);
zFrame.document.close();
},100);
}
The hack I suggested in chat:
var a = setInterval( function(){
try{
zFrame.contentWindow.document.write(zStuff.html);
zFrame.contentWindow.document.close();
clearInterval(a);
}
catch(e){}
}, 10 );
Since it is not known when IE allows accessing contentWindow properties, this will keep trying until it is allowed.

OK I am stumped!! IIS7 vs my javascript

I made a couple of changes to my javascript (which uses jquery ajax get). All I did was add an alert to see what was being sent. So the alert showd me what I wanted to see and I removed it from the script.
But now no matter what I do it keeps on popping up the alert. Somewhere somehow it seems to be cached. I cleared my browser cache. I even went onto a different system and it still pops up. When I remove all the code and I just leave an empty .js file it is fine. But the moment I put the code back it starts doing the alerts again.
I double tripled and double tripled checked again. I removed the 1 alert statement I had.
What must I do? Help thanks.
(function($){$.cabrowserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.cabrowser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.cabrowser=$.extend((!z)?$.cabrowser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.cabrowser.name,$.cabrowser.className,$.layout.name,$.layout.className].join(' '));}};$.cabrowserTest(navigator.userAgent);})(jQuery);
var caHref = window.location.href;
var numRand=0;
function pProcess()
{
var pname = "";
var phref = "";
var pqty = "";
var pcip = "";
var pcit = "";
var custa = "";
var custb = "";
var custo = "";
var prod = "";
var custd = "";
var caSURL = "https://"+caHref.substring(caHref.indexOf("/",0)+2,caHref.indexOf("/",7));
$.ajaxSettings.async = false;
$.ajaxSettings.cache = false;
function handle(table) {
custa = '&abanurl='+caHref;
custb = '&browser='+escape($.cabrowser.name+' '+$.cabrowser.version);
custo = '&os='+$.os.name;
custd = 'custfname='+escape(CustFName)+'&custlname='+escape(CustLName)+'&custemail='+CustEmail;
table.find('tr').each(function() {
pname = $(this).find('.PName a:first').text();
phref = $(this).find('.PName a:first').attr('href');
pqty = $(this).find('.Quantity input:first').val();
pcip = $(this).find('.IndividualP').text();
pcit = $(this).find('.TotalP').text();
prod+= '&pName='+escape($.trim(pname))+'&purl='+escape($.trim(phref))+'&pqty='+$.trim(pqty)+'&pcip='+$.trim(pcip)+'&pcit='+$.trim(pcit);
return false;
});
if (prod != "") {
CrossDomain();
$.get('https://www.SOMEWEBSITE.com/default.asp?'+custd+prod+custa+custb+custo+'&rnd='+numRand, function(){return false;});
}
}
if (caHref.search('finish.php')==-1)
{
var table = $('<table/>');
table.load('/mypage.php?Check=1 .Contents tbody', function(){handle(table);});
} else if (caHref.search('finish.php')>-1) {
CrossDomain();
$.get('https://www.SOMEWEBSITE.com/cart/?custemail='+CEmail+'&fin=1&rnd='+numRand, function(){return false;});
}
if (prod=="" && caHref.search('finish.php')==-1)
{
CrossDomain();
$.get('https://www.SOMEWEBSITE.com/default.asp?'+custd+custa+custb+custo+'&rnd='+numRand, function(){return false;});
}
};
if ( $.cookie("YouAreLogin")!=null && caHref.search('Check')==-1 )
{
$(document).ready(function() {
$('#frm input[type="image"]').click(function () {
$.get('https://www.SOMEWEBSITE.com/mypage.asp?product='+caHref+'&rnd='+numRand, function(){return false;});
});
});
pProcess();
}
function CrossDomain()
{
$.ajaxSettings.crossDomain = true;
$.ajaxSettings.timeout = 5000;
$.ajaxSettings.jsonp = false;
$.ajaxSettings.dataType = "jsonp";
numRand = Math.floor(Math.random()*9999999) + parseFloat(1000);
}
The numRand I added to see if that would work. The link to the website I have replaced as at the moment it is not puplic knowledge.
Looks like a caching issue.
Can you first check to make sure if it is/is not a caching issue. You can check the HTTP response code for the js file you are using ( user Firebug in Firefox, it should be other than 304 Not Modified).
Also check to make sure that the content of the js file that is transffered has alerts in it or not.
Can you post back what you see after that here?
Well only option left which sorted it out! I never want to go through this again! We uninstalled IIS and reinstalled. Problem sorted. What a nighmare! Thanks to all those who picthed in. I really appreciate it!
just had this occur on my local dev environment - win7 64 bit enterprise SP1 - IIS7 - VS2010 - javascript is inside an old classic site running thru IIS7 not studio's internal server.
Possible clue: have never had this happen to me until i created an active x control for the site...
first - what worked: runnign CCLeaner over the system - all cookies and registry clean - restart and sigh finally working.
tried (all failed):
iisreset
updating affected files, writing alerts into the code
recycle app pools / stop / start site
added no-cache rules for .asp, .js in IIS7
close re-open studio, close all restart computer.
delete temp files C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
uninstall IIS and re-install IIS
This was a javascript file included by classic asp pages - so where does the system cache js files i wonder? users/temp internet or something?

Return address of image or error if it doesn't exist

I know my problem is the fact that I can't check if the image is good until it has time to load. I'm trying to check width and return after it or the src changes (using onerror to set an src.) I'm always getting stuck with a race condition though, and it errors out long before the height and width or src change. When I reload, the image is cached and it works fine. I don't know how to avoid this. Here is my current code (also not working, it loops until Firefox complains.) I'm setting the return of this function to a variable. There are some writes in there I'm using to see how far it gets, and it stops in the while loop. I tried using getTimeout('tstit = chkload("thisisatest",tinypth);',250);, but that didn't work either. I wish I could force this to load in order...
function buildimg(tehname,myc,pth1,pth2,tinypth)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
buildtest("thisisatest",myimg,tinypth);
var testimg = document.getElementById("thisisatest");
var tstit = chkload("thisisatest",tinypth);
while(tstit == false) {
document.write(tstit);
tstit = chkload("thisisatest",tinypth);
}
alert(testimg.src+'-'+testimg.width+'-'+testimg.height);
if((testimage.width > 20) && (testimage.height > 20)) {
return myimg;
}
else if(typeof pth2 == "undefined") {
myimg = "error";
return myimg;
}
else {
myimg = buildimg(tehname,myc,pth2);
return myimg;
}
document.write('No return error in buildimg.');
return "error";
}
/*Builds a hidden img tag for testing images*/
function buildtest(itsid,itssrc,tinypath) {
if(document.getElementById(itsid)) {
var imgobj = document.getElementById(itsid);
imgobj.remove();
}
document.write('<img id="'+itsid+'" style="display: none;" src="'+itssrc+'" onerror="swaponerr(\''+itsid+'\',\''+tinypath+'\')" />');
}
/*Swaps the image to a small picture, so we can detect if it worked*/
function swaponerr(tagid, tinypath) {
var theimg = document.getElementById(tagid);
theimg.onerror = '';
theimg.src = tinypath;
}
/*Recurses to return when the image is loaded*/
function chkload(loadid,tinychk) {
var tehobj = document.getElementById(loadid);
document.write(tehobj.width+'x'+tehobj.height+'x'+tehobj.src);
if((tehobj.naturalWidth > 20) && (tehobj.naturalHeight > 20)) {
return true;
}
if(tehobj.src == tinychk) {
return true;
}
return false;
}
I need to test for an image, and return error if it is non-existent. The code below works fine on my server:
/*Checks if the image at /tehname/tehname-c.jpg exists in either of the paths
outputs it's address if it does, and "error" if not.*/
function buildimg(tehname,index,pth1,pth2)
{
var myimg = pth1+tehname+"/"+tehname+"-"+index+".jpg";
$.ajax({
url:myimg,
type:'HEAD',
error: function()
{
myimg=pth2+tehname+"/"+tehname+"-"+index+".jpg";
$.ajax({
url:myimg,
type:'HEAD',
error: function()
{
myimg="error";
return;
},
});
return;
},
});
return myimg;
}
Unfortunately, I'm trying to do this on a messed up system my work uses. We do have jquery, but the system stores user files on a separate server from code, so ajax won't work. This will eventually be in a .js file, I hope.
Now I've got code starting with:
function buildimg(tehname,myc,pth1,pth2)
{
var myimg = pth1+tehname+"/"+tehname+"-"+myc+".jpg";
var tehimage = new Image();
tehimg.src = myimg;
I tried to have the function load the image, and check its width, but I always get 0, since I can't pre-load the images without knowing how many they are (and I don't want to have some outrageously high number of requests with most being errors.) For some reason (at least on Firefox 4, as that's what my goal is to get working first) tehimage.complete always returns false. I've tried using onerror and onload by a global variable, and a few other methods. I must admit though, I'm not very versed in Javascript, so my callbacks may not have worked.
Please help, I'm getting desperate!
Do you hold the 'power to execute php code' on that user files server? If so, check them in php and output to images.js in that server, than in your html, first load images.js, then your usual javascript.
By the way, jQuery had memory leaks in ajax for ears, don't know about 1.6, but 1.5 definately had those. if you wan't to use ajax to get data from server to javascript - use plain javascript: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Edit: Definately worth checking out: http://fettig.net/weblog/2005/11/28/how-to-make-xmlhttprequest-connections-to-another-server-in-your-domain/
Since I'm getting no answers, I'm closing the question. What I ended up doing was a modification to make the image change class in the onload, have the image onerror delete it, and have the rest of the code run in the window onload. Unfortunately, this means the 404s aren't caught before it tries to load more images, so I'm forced to limit the max number of images that can be used (changeable in the function call,) and the images that aren't there just waste a little time.
See the final result here.

Blinking document.title and IE7 (no way ?)

i develop a website and i need let the document title blinking when the browser lost the focus to get the attention from the user.
This is a common task for example in some social network. Btw my javascript code work fine in Chrome, Firefox, Opera, but not in IE7 (that i am testing before release the site)
IE7 have a strange behavior because if i print the document.title in a debug text (you can see in the code), it's changed but the browser still show the previous document title
I try to search a lot on internet to try to fix this problem but with no luck so i decided to post the question in this site. Here my javascript code below and thanks in advance for the suggestions.
the JS method is called by this.blink(true)
// other methods above and below ....
this.blink = function(Action)
{
if (Action)
{
if (!this.blinking)
this.oldTitle=top.document.title;
else
clearInterval(this.blinkTimer);
// debug current title
$('debugText').value = 'ORIGINAL ' + top.document.title + '\n' + $('debugHistory').value;
this.blinkTimer = setInterval(function() {
var msg='MSG', newTitle
if (top.document.title == msg)
newTitle = '----';
else
newTitle = msg;
// assign title
top.document.title = newTitle;
// debug blinking, is really changed but not shown <---
$('debugText').value = 'BLINK ' + top.document.title + '\n' + $('debugHistory').value;
}, 1000);
}
else
{
clearInterval(this.blinkTimer);
if (this.blinking)
top.document.title = this.oldTitle;
}
this.blinking = Action;
}
If you're using jQuery, I've made a plugin called Title Alert for the purpose of blinking notification messages in the browser title bar. With it, you can specify different options like duration, blinking interval, if the blinking should stop when the window/tab gets focused, etc. I've verified that the plugin works in IE6, IE7, IE8, Firefox, Chrome and Safari.
Here is an example on how to use it:
$.titleAlert("New chat message!", {
requireBlur:true,
stopOnFocus:true,
interval:600
});
If you're not using jQuery, you might still want to look at the source code (there are a few quirky bugs and edge cases that you need to handle when doing title blinking if you want to fully support all major browsers).
Instead of top.document.title try top.document.getElementsbyTagName('title')[0] (This is assuming top is some form of frame or window)
Try this in IE
this.blink = function (Action)
{
if (Action)
{
if (!this.blinking)
this.oldTitle=top.document.title;
else
clearInterval(this.blinkTimer);
this.blinkTimer = setInterval(function() {
var msg='MSG', newTitle
if (top.document.title == msg)
newTitle = '----';
else
newTitle = msg;
// assign title
top.document.title = newTitle;
}, 1000);
}
else
{
clearInterval(this.blinkTimer);
if (this.blinking)
top.document.title = this.oldTitle;
}
this.blinking = Action;
}
window.blink('now');​​​​
Mostly it will be an issue that window.onblur etc. is not triggering your blink function. If the above works, then you can use mouse movement to track timeout.

Categories

Resources