Does window.onload not work consistently with some browsers..?
I've put a script together purposely utilizing native JavaScript (no library or framework used). I know there may be some issues with cross-browser compatibility. However, there is something different occurring with the Edge browser at least.
The entire page works as expected in webkit(Chrome, not yet in Safari), and it seems to work perfect in the latest Firefox as well.
In Microsoft's Edge browser it seems to have a starter issue, or, it's not booting well every time on the onload trigger. It works perfectly sometimes, if I refresh the page enough.
What can possibly explain this? Edge may be better in this case as I'm not sure if it's working in Safari at all.
Codepen link!
window.onload = function() {
// if you're savvy enough for it... please check codepen for the full code
/* automation from input */
wght_input.oninput = function() {
x = this.value;
var bodyweight = x;
// when puts into form input
this.onchange = function() {
frmFeed[0].innerHTML = "";
recc_wght();
getadd();
whatsTotal();
resetButton.click() ;
};
var kgs = curr_wght_set_amt * kg; //convert lbs lifted to kgs
logs("The highest recorded lift was " + curr_wght_set_amt.toFixed(0) + "lbs or "+ kgs +"kgs");
}; // end active oninput
}; // end onload function
use window.addEventListener instead:
window.addEventListener('load', yourFunc, false);
You'd have to wrap everything else in a named function (yourFunc)...
Related
I m a newbie to programming in JS, i though of giving a try in intel XDk.
I browsed some videos and according to one tutorial, i followed the exact same steps as he did,
But unfortunately, he got the script in emulator working while mine got stuck with a problem of `alert is not defined (W117)' but he didn't got that error,.
My JS code as follows:
/*jshint browser:true */
/*global $ */(function()
{
"use strict";
/*
hook up event handlers
*/
function register_event_handlers()
{
/* button #submit */
$(document).on("click", "#submit", function(evt)
{
/* your code goes here */
var name = document.getElementById('name').value;
var place = document.getElementById('place').value;
var job = document.getElementById('job').value;
var gender = document.getElementById('gender').value;
var reason = document.getElementById('reason').value;
var text = name + place + job + gender + reason ;
alert(text);
return false;
});
}
document.addEventListener("app.Ready", register_event_handlers, false);
})();
Any help is appreciated..
I don't have your full JS code and cannot find an 'app.Ready' event (which is being run on load looks like). To perform check based on jQuery 'ready' event just use below code:
$(document).on("click", "#submit", function(evt) {
var name = document.getElementById('name').value;
var place = document.getElementById('place').value;
var job = document.getElementById('job').value;
var gender = document.getElementById('gender').value;
var reason = document.getElementById('reason').value;
var text = name + place + job + gender + reason;
alert(text);
return false;
});
With the 3900 (and later) releases of the XDK there is a known issue where the alert() (and related) functions no longer work inside the Simulate tab. This was due to an upgrade of the version of Chromium that is built into the node-webkit image that underlies the XDK. At this time there is no workaround, other than to use the Cordova dialogs plugin as an alternative.
Note that in some WebViews (the runtime that your Cordova app runs in when it runs on a real device) the alert() function does not exist, since it is an optional feature and not required. Keep in mind that your Cordova app does not actually run in a browser, it runs in an embedded runtime that feels a bit like a browser, but it's not. Just like Node.js apps have a JavaScript runtime engine, so do WebViews, but neither runtime is hosted within a browser.
In general, using the alert() function is not a good option for a real app.
I have written a jquery addon, with a little help from the internet, which retrieves data from Facebook and does as intended on all browsers tested so far apart from IE9.
I work for local government and unfortunately we still use IE9 in our builds (It was still IE8 a few weeks back!! So could have been a lot worse I expect :).
Anyways, I digress, I have added the section of code below which never completes in IE9, but does in IE10, and other browsers...
Can anyone explain/help me adapt or fix this snippet so that I can get it working in IE9?? And not break it in any other browsers in the process :)??
$.when($.getJSON(ogUSER), $.getJSON(ogPOSTS)).done(function (user, posts) {
// user[0] contains information about the user (name and picture);
// posts[0].data is an array with wall posts;
var fb = {
user: user[0],
posts: []
};
var idxLimit = 0;
$.each(posts[0].data, function () {
// We only show links and statuses from the posts feed:
if (this.type != 'link' && this.type != 'status') {
return true;
}
// Copying the user avatar to each post, so it is
// easier to generate the templates:
this.from.picture = fb.user.picture.data.url;
// Converting the created_time (a UNIX timestamp) to
// a relative time offset (e.g. 5 minutes ago):
this.created_time = relativeTime(this.created_time * 1000);
// Converting URL strings to actual hyperlinks:
this.message = urlHyperlinks(this.message);
//remove all anchors
//var content = $('<div>' + this.message + '</div>');
//content.find('a').remove();
//this.message = content.html();
fb.posts.push(this);
idxLimit++;
if (idxLimit === 2) {
return false;
}
});
In all browsers, not including IE9, if I insert a breakpoints anywhere within the .done() callback it stops execution and I can debug. With IE9 the breakpoint is not reached leading me to believe there is an issue with IE9 script engine and jQuery.when() API call, or the .done() callback method...
But, I'm just guessing at the mo... I've been searching the web for the last few hours to see if anyone else has happened upon a similar issue but to no avail. I hope some of the more experienced coders here can help... would be very much appreciated. Until then the search goes on :)
Thanks for your time folks ;)
PS. I don't receive any console errors what so ever in IE9 running the script...
TartanBono
I have an embedded Youtube video, and I want to capture events when the user pauses the video, skips around, etc. Following the examples at Google's documentation (http://developers.google.com/youtube/js_api_reference), I do the following:
var video = (my video ID here);
var params = { allowScriptAccess: "always" };
var atts = { id: "youtubeplayer" };
var x = 854;
var y = 480;
swfobject.embedSWF("http://www.youtube.com/v/" + video + "?enablejsapi=1&playerapiid=ytplayer&version=3", "bobina", x, y, "8", null, null, params, atts);
function onYouTubePlayerReady(playerId) {
youtubeplayer = document.getElementById('youtubeplayer');
youtubeplayer.addEventListener("onStateChange", "onytplayerStateChange");
youtubeplayer.setPlaybackQuality('large');
}
function onytplayerStateChange(newState) {
//Make it autoplay on page load
if (newState == -1) {
youtubeplayer.playVideo();
}
var tiempo=youtubeplayer.getCurrentTime();
//Rounds to 2 decimals
var tiempo = Math.round(tiempo*100)/100;
alert(tiempo);
}
Now, all this works perfectly in Firefox and Safari, but there's no way to make it work in IE8 (by which I mean: the video loads, but events aren't captured: the event handler never gets called). According to javascript addEventListener onStateChange not working in IE , IE doesn't support addEventListener(), so I tried replacing that line with:
youtubeplayer.attachEvent("onStateChange", onytplayerStateChange);
But it doesn't work either. (The author of that question says that he finally solved it by putting "onComplete in my colorbox and put the swfobject in that", but I'm not using a colorbox here (I don't even know what that is), so I don't understand what he means.
Using alerts() to debug, I see that the first function (onYoutubePlayerReady()) is indeed called, but I can't even tell whether the event listener isn't being registered or whether it's the getElementById() that isn't working; I tried debugging by adding a:
alert(typeof youtubeplayer);
Right after it, but it doesn't even pop up.
Oh, and one more thing: the video starts automatically in Firefox and Safari, but in IE it doesn't either. (And yes, I'm running this on a server, not on a local page).
Anyone has any ideas? I don't really know what else to try.
Okay, found the solution. Guess what it was? Just write is as:
var youtubeplayer = document.getElementById('youtubeplayer');
And it works perfectly in IE 8. All it needed was the "var" keyword.
Just in case it's useful for someone else with the same problem...
Is there a way to tell, after the fact, whether an image (placed with the <img> tag, not via JS) has loaded correctly into a page? I have a gallery of head shots, and occasionally the third-party image server ends up serving up a 404. I can change the server-side code to use an onerror="showGenericHeadshot()", but I really want to avoid making changes to server-side code. Ultimately, I want to determine if an image is missing or broken and replace it with a generic "Image Not Found" graphic. Things I've tried:
Image.prototype.onerror = showGenericHeadshot -- doesn't work for <img> tags
$('img[src*=thirdpartyserver.com]).error(showGenericHeadshot) -- doesn't work in IE
$('img[src*=thirdpartyserver.com]).css('backgroundImage','url(replacementimage.gif)') -- works, but still doesn't get rid of the broken image icon in IE
<img scr='someUrl' id="testImage" />
jQuery('#testImage').bind('load',function(){
alert ('iamge loaded');
});
to avoid race condition do as below
<img _src="http://www.caregiving.org/intcaregiving/flags/UK.gif" />
// i have added an underscore character before src
jQuery('img').each(function(){
var _elm=jQuery(this);
_elm.bind('load',_imageLoaded).attr('src',_elm.attr('_src'))
});
function _imageLoaded()
{
alert('img loaded');
}
Unfortunately, I'm not able to accept either #TJ Crowder's nor #Praveen's excellent answers, though both do perform the desired image-replacement. #Praveen's answer would require a change to the HTML (in which case I should just hook into the <img> tag's own error="" event attribute. And judging by network activity, it look like if you try to create a new image using the url of an image that just 404ed in the same page, the request actually does get sent a second time. Part of the reason the image server is failing is, at least partly, our traffic; so I really have to do everything I can to keep requests down or the problem will only get worse..
The SO question referred to in #danp's comment to my question actually had the answer for me, though it was not the accepted answer there. I'm able to confirm that it works with IE 7 & 8, FF and webkit browsers. I'm doubtful it will work with older browsers, so I've got a try/catch in there to handle any exceptions. The worse case will be that no image-replacement happens, which is no different from what happens now without doing anything. The implementation I'm using is below:
$(function() {
$('img[src*=images.3rdparty.com]').each(
function() {
try {
if (!this.complete || (!$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0))) {
this.src = 'http://myserver.com/images/no_photo.gif';
}
} catch(e) {}
}
);
});
Would an alternate text be sufficient? If so you can use the alt attribute of the img tag.
I think I've got it: When the DOM is loaded (or even on the window.load event — after all, you want to do this when all images are as complete as they're going to get), you can retroactively check that the images are okay by creating one new img element, hooking its load and error events, and then cycling through grabbing the src from each of your headshots. Something like the code below (live example). That code was just dashed off, it's not production quality — for instance, you'll probably want a timeout after which if you haven't received either load or error, you assume error. (You'll probably have to replace your checker image to handle that reliably.)
This technique assumes that reusing a src does not reload the image, which I think is a fairly reliable assumption (it is certainly an easily testable one) because this technique has been used for precaching images forever.
I've tested the below on Chrome, Firefox, and Opera for Linux as well as IE6 (yes, really) and IE8 for Windows. Worked a treat.
jQuery(function($) {
var imgs, checker, index, start;
// Obviously, adjust this selector to match just your headshots
imgs = $('img');
if (imgs.length > 0) {
// Create the checker, hide it, and append it
checker = $("<img>").hide().appendTo(document.body);
// Hook it up
checker.load(imageLoaded).error(imageFailed);
// Start our loop
index = 0;
display("Verifying");
start = now();
verify();
}
function now() {
return +new Date();
}
function verify() {
if (!imgs || index >= imgs.length) {
display("Done verifying, total time = " + (now() - start) + "ms");
checker.remove();
checker = undefined;
return;
}
checker[0].src = imgs[index].src;
}
function imageLoaded() {
display("Image " + index + " loaded successfully");
++index;
verify();
}
function imageFailed() {
display("Image " + index + " failed");
++index;
verify();
}
function display(msg) {
$("<p>" + now() + ": " + msg + "</p>").appendTo(document.body);
}
});
Live example
I've written a userscript for Gmail : Pimp.my.Gmail & i'd like it to be compatible with Google Chrome too.
Now i have tried a couple of things, to the best of my Javascript knowledge (which is very weak) & have been successful up-to a certain extent, though im not sure if it's the right way.
Here's what i tried, to make it work in Chrome:
The very first thing i found is that contentWindow.document doesn't work in chrome, so i tried contentDocument, which works.
BUT i noticed one thing, checking the console messages in Firefox and Chrome, i saw that the script gets executed multiple times in Firefox whereas in Chrome it just executes once!
So i had to abandon the window.addEventListener('load', init, false); line and replace it with window.setTimeout(init, 5000); and i'm not sure if this is a good idea.
The other thing i tried is keeping the window.addEventListener('load', init, false); line and using window.setTimeout(init, 1000); inside init() in case the canvasframe is not found.
So please do lemme know what would be the best way to make this script cross-browser compatible.
Oh and im all ears for making this script better/efficient code wise (which im sure is possible)
edit: no help...? :'(
edit 28-Apr:
i re-wrote the code a little and now it looks something like this.:
if(document.location != top.location) return;
(function() {
var interval = window.setInterval(waitforiframe, 3000);
var canvas;
function waitforiframe() {
console.log("Finding canvas frame");
canvas = document.getElementById("canvas_frame");
if (canvas && canvas.contentDocument) {
console.log("Found canvas frame");
pimpmygmail();
}
}
function pimpmygmail() {
gmail = canvas.contentDocument;
if(!gmail) return;
window.clearInterval(interval);
console.log("Lets PIMP.MY.GMAIL!!!");
......rest of the code......
})();
This works perfectly fine in Firefox, but in Chrome, it gives me a top is undefined error.
Another thing i noticed is that if i remove the first line if(document.location != top.location) return; , the waitforiframe() method keeps getting called over and over again. (ie i see the "Finding canvas frame" error in the console)
can someone tell me what does the first line do? i mean what does it achieve & why does the waitforiframe() method run forever if i remove that line??
A BIG THANK YOU TO ALL WHO HELPED! -_- meh
btw, this was all i needed at the beginning of the script:
try { if(top.location.href != window.location.href) { return; } }
catch(e) { return; }