Problem using onload javascript - javascript

I have used Javascript onlaod like this:
function check()
{
var pic = new Image();
pic.src= "images/first.jpg";
pic.onload = function()
{
alert("Uploaded");
}
}
This is html code where the function is called.
<input type="button" onclick="check()" value="Check" />
It works for both safari and firefox. But with IE, first time it works but when I click on check Button next time it does not work. It also works when cache is cleared.
Can anyone help me what problem might occur here.
Thanks in advance

This should not be a problem in IE8.
IE6 (not sure about 7) is notoriously eager to use cached files, and when taking from the cache the load is not correctly calculated (I recall there being an interesting bug report on this, look for it on MS's site).
It can be solved by adding a [useless] parameter that forces a reload of the cached file:
pic.src= "images/first.jpg?nocache="+Math.random()

perhaps the onload() is too early?
jquery uses a function
$(document).ready(function(){}
that is executed when the page has finished loading.
Perhaps you need some similar function.

Related

Using JQuery to delay loading of div, code not working in Chrome (window.onload)

I'm using the code below to delay the loading of a div until the entire web page is loaded. It works perfectly in Firefox and Safari (because they each have lines in the code to make sure it works specifically for each, I haven't tested IE yet), but not in Chrome (which should, I think, work with window.onload).
Could somebody please help me out with this?
<script type="text/javascript">
function insertFB(){
var html='<div class="fb-page" data-href="https://www.facebook.com/bobcaputolivingwell" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/bobcaputolivingwell">Bob Caputo Living Well</blockquote></div></div>';
$("#FB_PAGE").html(html);
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", insertFB, false);
}
if (/WebKit/i.test(navigator.userAgent)){
var _timer = setinterval(function(){
if(/loaded|complete/.test(document.readyState)){
insertFB();
}
},10);
}
window.onload = insertFB();
</script>
Well, firstly I'll answer specifically your question:
It's not working in Google Chrome, because you're using setinterval, and Javascript is a case-sensitive language. The correct name of the method is setInterval.
Besides that, your code is full of errors, you check for a method inside document, and don't use else if to check the others, so you always check all, and probably call the method you want two or more times.
The other thing is that you're using setInterval but you're never clearing the interval, so that thing is gonna run every 10ms forever.
And finally, the last thing, you're calling the insertFB function when you're trying to attach it to the onload event. You shouldn't be using parenthesis for that.
Take a look at Can I use addEventListener? and at Can I use DOMContentLoaded?, and you'll see that it's supported by all major browsers, even some old ones, and you should only use another way, if you really need to support IE8 (nowadays it's unlikely).

JavaScript button fires perfectly in Chrome and IE but won't work in Firefox

I'm sure the title looks like something that's been asked before but I've searched for the answer to this and I can't find it.
I'm really very new to coding, so please excuse any really obvious mistakes I've made.
Context to the code I'm working on: I'm in a Game Design class and I've decided to take up a personal project making an HTML JS game.
I understand that the code is possibly rough / bad / definitely-not-the-best-way-to-do-things, but it will continue to be so until I improve my skills (or am given advice on how to improve it).
What I need help with: For two to three weeks, I could not figure out how to get a button to appear when implemented inside of an if else statement.
Like so:
if(condition)
{
document.write("text");
//desired button here
}
else
{
//Backup code
}
Eventually I figured two ways to do that (for Chrome and Internet Explorer).
First way:
function myFunction()
{
document.close();
document.write("text");
/* There will be buttons in here
too when I get things working. */
}
//In separate script tags
/* myFunction() dwells in the head of the
page while the if statement is in the body
and another function*/
if(condition)
{
document.write("text");
var gameElement=document.createElement("BUTTON");
var text=document.createTextNode("CLICK ME");
gameElement.appendChild(text);
gameElement.onclick = myFunction;
document.body.appendChild(gameElement);
}
else
{
//Backup code
}
The second way:
(The same function, they're both in the same places).
if(condition)
{
document.write("text");
var gameElement;
gameElement = document.createElement('input');
gameElement.id = 'gameButton';
gameElement.type = 'button';
gameElement.value='Continue';
gameElement.onclick = myFunction;
document.body.appendChild(gameElement);
}
This works well for me.
And while it works in IE and Chrome fine, it doesn't work in Firefox.
After how much time and research I've put into just this button, I'd love to know why it won't show up in Firefox. I've read a lot about Firefox and how .onclick won't work or something like JavaScript has to be enabled or disabled. I'm just a bit confused.
I'm also open any real / relevant advice.
I set up this fiddle. I removed your document.write() calls because they're disallowed in JSFiddle, and change your condition to true so the code would work, and it works in FF24.
document.write() might be the cause of your problem. It's bad practice anyway because it can cause a re-parse of a document, or wipe the entire document and start writing it again. You're already using some DOM manipulation to add the button. I suggest you do likewise for anything you're considering using document.write() for.
Instead of suggesting a solution to your problem, I would suggest you take a look at jQuery, which is a very nice JavaScript framework, that makes it possible for you to write cross-browser compatible code, which it seems is your problem here.
Using jQuery, you would be able to write something like:
$("#gameButton").click(function() { myFunction(); }
which would trigger your myFunction() function, when the control with the id 'gameButton' is clicked.
Visit www.jquery.com to learn more

Javascript setInterval not working in Internet Explorer

When using setInterval to call a function that refreshing webcam images within the html body. This works well in Chrome, however, in Internet Explorer the images are not refreshing. Is this because of a caching issue?
<img id='camA' class='webcamStill' src='http://10.0.0.157/jpg/image.jpg' alt='Cam Image' />
window.setInterval(refreshWebcam, 3000);
function refreshWebcam()
{
$('#camA').attr('src', 'http://10.0.0.157/jpg/image.jpg');
}
Absolutely. You are setting the source to what it already is, so it's not actually changing, so no need to update as far as the browser is concerned.
To cachebust, just do this:
document.getElementById('camA').src =
"http://10.0.0.157/jpg/image.jpg?x="+new Date().getTime();
I used Vanilla JS because reasons.

How to check dynamic javascript value with Jquery with IE

I am stuck on this, please help!
I have an external Javascript that inserts code on my page. Among other things it inserts an image wrapped in a div. I do not have control over the script, but I would like to change the image path/url using Jquery.
This is what I have done:
$('.ProductImage img').attr('src',function(index,attr){
return attr.replace('small','original');
});
Works like a charm in all browsers except IE.
When checking the selector with alert(), IE returns %Thumbnail% which is the Javascript variable/object. I have tried wrapping my script in a timeout to allow IE to finish loading but no luck.
Any ideas?
Thanks in advance!
Have you tried wrapping your code inside $(function(){ .. }) so that it will run after the document finished loading?
If your script is not loaded by the time your code gets executed you could try putting the code inside window.onload
window.onload = function(){
replaceImages();
};
function replaceImages(){
$('.ProductImage img').attr('src',function(index,attr){
return attr.replace('small','original');
});
}

Javascript callback not firing when AJAX operation complete

Given the following code on an ASP.NET MVC View:
<% using (Ajax.BeginForm("AddCommunity",
new AjaxOptions { UpdateTargetId = "community-list",
OnSuccess = "BindCommunityHover" }))
{ %>
Add Community: <input type="text" id="communityName" name="communityName" />
<input type="submit" value="Add" />
<% } %>
And the following JavaScript method in the file:
function BindCommunityHover() {
$(".community-item-li").hover(
function () { $(this).addClass("communityHover"); },
function () { $(this).removeClass("communityHover"); }
);
};
Is there any reason why BindCommunityHover is not being called when the AJAX result comes back?
The community-list div is properly updated (the action returns a partial view). I have also tried setting OnComplete (instead of OnSuccess) to no avail.
The BindCommunityHover method is called in a $(function(){...}); block when the page first loads, and for all existing .community-item-li elements, it works.
The partial result from my controller replaces all items in that div with more of the same class. The OnSuccess method is supposed to fire after the document is updated.
Update: k...this gets weird. I added the following to the BindCommunityHover method:
alert($(".community-item-li").size());
I'm getting 240 in the alert when the page loads and when the callback fires. So, the callback IS firing, jQuery is matching the elements but not applying the styles...
That's because your function is basically saying add a hover event for all of these items as they exist at the point in time when the function is called.
If you then add new elements they aren't automatically bound. There is a new feature in JQuery called Live Events. I've not dug into them but I think they might help here. Otherwise as you add new elements be sure to bind the hover functions.
Okay, there were two parts to this solution.
First culprit was some nasty caching thing that I can't figure out in Cassini/IE. I tried rebooting, stopping Cassini, restarting VS2010...nothing worked.
The code still won't work on IE on my account on this computer. The deployed-to-IIS version works on all browsers. It also works in IE if I change the filename. Something is borked there, though. If I run the project with Cassini/IE, then open FireFox and go to the site, it works.I tried to repro the error to file a bug, but I can't get it to go. I digress. To get around this I changed the name of the .js file and moved the reference to a different spot in the master page.
The other thing was that I did have to use OnSuccess. I switched to using OnComplete when I was trying to figure out what was wrong. After I figured out the file/browser/server problem, I realized that OnComplete (per the docs) fires before the document is updated; the elements were being updated but then thrown away.
The OnSuccess/OnComplete might help sort something out for someone, not sure about the file/browser/server issue...that might be environmental.

Categories