Setting an image source via Javascript unreliable in Internet Explorer - javascript

I am simply trying to change the SRC attribute of an image via javascript like so:
document.getElementById('fooImage').src = img;
Where img is a variable that has a link to the file.
In all other browsers (Chrome, Firefox, Safari) this works. In IE (7+) this also works too sometimes.
Using IE's built-in developer tools, I can see that the image's SRC tag is set. Is there something else in the locals window that could help me debug why the image doesn't actually show on screen?
I've also tried using jQuery to do this and same outcome:
$("#fooImage").attr("src", img);
An ideas?

In debugging this I would hard code it first...
document.getElementById('fooImage').src = "myimage.png";
I've used the following in my website and it works like this...
var imgCounter = document.getElementById('formtimer');
imgCounter.src = "graphics/odometers/1.png";
Some other things to check:
Make sure your ID= tag is not in the <DIV section but inside the <IMG section... for example <div class="style1"><img src="yourpicture" id="someid">. If `id='someid' is in the div tag then you can't change the picture / the picture won't show up.
are you using window.onload?, body onload? the proper way to use the first is..
window.onload = function () { YourFunctionHere(); };
Try a different test image. I had issues in the past with showing png's, I changed it to a gif or jpg and it worked. I don't understand how that was "way back" but it doesn't seem to be an issue anymore but hey... something to try.
try a full url
using https?
try sticking the image somewhere else in your program and see what happens.
try adding this to your HTML (put your website in place of mine - lookup BASE href on google for more info)
<BASE href="http://perrycs/" />
Make sure the image isn't hidden behind a layer (I know it works in some browsers)
tell us the website so we can check it out and get more info to help you in debugging this, seeing context (surrounding code) helps...

Given that it works in other browsers, searching on this topic it seems that often the problem is how IE caches images (ref. Epascarello's comment). Your code is the same as what I have - it works fine except in IE10.

I too, faced this conundrum. Then discovered that it works in 'Page Inspector', so after some digging discovered that (in Internet Explorer) by going to Tools.Internet Options.Advanced
uncheck the 'Disable script debugging (Internet Explorer)' and the one below it.

I found that with IE9 after changing an image.src with
var strVar="C:Users/x/Desktop/caution.png"
image.src=strVar
and calling an alert(image.src) I would get something like this n the alertbox:
file:///C:Users/x/Desktop/"C:Users/x/Desktop/caution.png"
So I tried
image.src=strVar.replace(/\"/g,"")
to remove qoutemarks
and it worked!
alert(image.src)
file:///C:Users/x/Desktop/caution.png

Related

An issue with src(unknown) - broken image in Chrome

I am having a really strange behavior in Chrome when I try to display images.
I see some little badges with breaking images like that:
This is just broken image picture.
It didn't work like that in chrome before.
I use some javascript code to handle not found images:
//This script will be loaded in head section of the page
function fixBrokenImage(element) {
element.onerror = '';
element.src = '';
}
And in HTML:
<img src="~/Image?getById=#Model" onerror="fixBrokenImage(this)"/>
However, it only works in Chrome for the first time when I do Clear Cache and Hard Refresh and does not work in subsequent normal refreshes
It is ashamed to say but it works in IE and Edge which feels a little bit funny.
Do you know maybe how can I fix it in Chrome.
I am using version: Version 63.0.3239.108 (Official Build) (64-bit)
Thanks for any suggestions
You can use this javascript code like this, you forgot to put alt attribute:
function fixBrokenImage(element) {
element.onerror = '';
element.src = '';
element.alt = 'image not found'
}
I managed to make it working by adding empty attribute to the html element:
<img src="~/Image?getById=#Model" onerror="fixBrokenImage(this)" alt=""/>
Thanks #Teemu for your suggestions which eventually made that code work on Chrome
if you are using php then esc_url($url) will solve it, esc_url function solves the problem or just use URL.createObjectURL(url) simply in Js

document.getElementById("").getElementsByTagName("img")[0].src = Not Working

I have these 3 lines of code in an external javascript file
function init(){
document.getElementById("upcoming_event").getElementsByTagName("img")[0].src = "images/fastnet_2013_poster.jpg";
document.getElementById("club_championship").getElementsByTagName("img")[0].src = "images/club_championship.png";
document.getElementById("setMembership").getElementsByTagName("img")[0].src = "images/join_our_club.png";
}
document.addEventListener( "DOMContentLoaded" , init , false);
This code works perfectly on this site which i used just to develop a little bit of it with 000webhosting.
But I have now moved my hosting to hosting24 to complete the development of the site. When i load the site through the new host(hosting24) the images are not getting loaded.
I have taken these 3 line of code out and tried them in an <body onload="init()"> but this dose not load the images either.
I know that both methods above are being called as i have got them to display a window.alert("Display").
Is there another way of doing this?
(document.getElementById("upcoming_event").getElementsByTagName("img")[0].src = "images/fastnet_2013_poster.jpg";) that i could try and use? Or solve my problem.
Changing servers should not effect javascript code at all. Only thing that comes to mind is that the URL's for the images sources isn't correct anymore, because of the move.
First you can use jQuery to help you do this in a simpler way like:
$('#upcoming_event').find('img')[0].src = "url";
or
$('#imgid').attr('src', 'xpto.jpg');
Secound, the code seems to work... I think the problem may be in the urls of the IMGs. Check if the images are in the correct folder or if the path is right.

Create an iframe then append data to it with jQuery

I am trying do some modification to an greasemonkey userscript to implement a feature I need. The code is like
showAddress:function(addrString,type)
{
this.addrBox=$('<div id="batchPublish"></div>')
.append('<div id="batchHeader"></div>')
.append('<div id="batchContent" style="float:left;clear:both"></div>');
.........
var batchContent=this.addrBox.find('#batchContent')
.append('<pre width="300" style="text-align:left" id="batchedlink"></pre>');
this.addrBox.find('#batchedlink').css({'width':'500px','height':'250px','overflow':'auto','word-wrap': 'break-word'})
.append(addrString);
$.blockUI({message:this.addrBox,css:{width:"520px",height:"300px"}}); }
Basically this code writes data to html. What I want to implement is to have "addrString" written to an iframe embedded. Now It's in the "pre" tag. I have tried many approaches but still no luck. Iframe was always empty.
I am completely a novice in javascript and unclear whether this is possible.
Thank you for the help.
Since you are adding the iFrame in the same domain, then you can manipulate its contents like this:
(See it in action at jsBin.)
$("#batchContent").append ('<iframe id="batchedlink"></iframe>');
/*--- Compensate for a bug in IE and FF, Dynamically added iFrame needs
some time to become "DOM-able".
*/
setTimeout ( function () {
var iframeBody = $("#batchedlink").contents ().find ("body");
iframeBody.append (addrString);
},
333
);
NOTE:
For a Chrome userscript, you apparently don't need the timer delay. But for FF and IE 8 (the other 2 browsers I double-checked), a dynamically added iFrame is not manipulable until after it has "settled" for some reason. This seems to take about 200 mS.
A statically loaded iFrame does not have this lag, see the jsBin demo.
Sort of hard to tell exactly what you're asking -- but if you want to know whether or not you can append DOM elements to an iFrame, the answer is "no".

Dynamically loaded <script> tag not being used in WebKit browsers

It seems this is a known problem and has been asked several times before here in SO however I do not see anything specific to jQTouch so I thought I would give it a try.
jQT will dynamically load pages when a link is clicked. In this page I would like to include something like
<script>
$.include('javascriptfile.js', function() {alert('do something with results of this file to an already existing div element');};
</script>
The $.include is a jquery plugin I found that mimics the $.load with a few more smarts added to it. Tested to work on FF but not in Chrome or most importantly, Safari.
The alert is never displayed. FireBug never shows the javascript even being loaded. If I put an alert before the $.include I still do not see anything.
I have tried an onclick/ontap event that would then run this code that was included in the head tag, no luck.
Edit: I am using the r148 revision of jQT. This was working prior to moving to this version, i believe.
Did you try to add the javascript file using one of these two methods:
Static Way:
<script type="text/javascript">
function staticLoadScript(url){
document.write('<script src="', url, '" type="text/JavaScript"><\/script>');
}
staticLoadScript("javascriptfile.js");
modifyDivFn(processFnInFile());
</script>
Dynamic way:
<script type="text/javascript">
function dhtmlLoadScript(url){
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
}
onload = function(){
dhtmlLoadScript("javascriptfile.js");
modifyDivFn(processFnInFile());
}
</script>
After the include you can call a function that does the processing you want (that being processFnInFile()) which result will be passed to modifyDivFn (and modify the div you want.) You could do this in one function, just to illustrate the idea.
Source: Dynamically Loading Javascript Files
Well Geries, I appreciate your help but ultimately the answer required a drastic rethinking of how I was using JQTouch. The solution was to move everything to an onclick event and make all the hrefs link to #. This might be what you were talking about Geries.
In the onclick function I do the logic, preloading, loading of the page through my own GET through jquery, then use the public object jQT.goTo(div, transition). This seems to get around the WebKit bugs or whatever I was running into and this now owrks on FireFox, Chrome, Safari, iPhone, and the lot.
I do run into a few animation issues with JQT but I think these are known issues that I hope Stark and the gang at JQTouch are working on.

shift-reload in FF gives unexpected results

I'm presenting a simple animation using img.src replace and the <canvas> tag. At present it's only expected to work in FireFox (FF 3.5.3, Mac OS X 10.5.5), so cross-browser compatibility isn't (yet) an issue.
When the page is first loaded, or loaded into an new window or tab, all seems to work as expected, and the cache behavior on a simple reload does not seem to be an issue; however, if I try to force a reload with shift-reload, I get a problem. Even though the images have been pre-loaded, the preloaded images for the animation don't seem to be available to the browser which then tries to load each new img.src from the server.
Am I looking at a browser bug here, or is there something buggy in my code that I can't see? This is my first shot at implementing a js class, so there might be a lot here that I don't understand.
Any insight from the assembled wise here would be welcome. You can see what I'm talking about at:
http://neolography.com/staging/mrfm/spin-sim.html
Thanks,
Jon
When you shift reload you're telling the browser to reload - not from the cache.
So it shouldn't be a surprise that you're getting the images from the server.
Images can be preloaded in javascript with the following code:
img = new Image();
img.src = "your/image/path";
If you want the images loaded before you use them that might help.
I had a look at your code and you have the following in document.ready()
function countLoadedImages() {
loadedImgs++;
if (loadedImgs == images.length){
$("#loading-image").hide();
$("#controls").fadeIn(100);
}
}
animation = new simAnim("snap", "stripchart", 800, deriveFrameData(spindata));
the animation = new simAnim line is executed regardless if all 100 images are loaded or not...
One possibility to fix this would be to move that line inside the countLoadedImages function like so:
function countLoadedImages() {
loadedImgs++;
if (loadedImgs == images.length){
$("#loading-image").hide();
$("#controls").fadeIn(100);
animation = new simAnim("snap", "stripchart", 800, deriveFrameData(spindata));
}
}
this way that function will be executed once all the images have loaded
Thanks to ekhaled, who tried. I'm now satisfied that this is a browser bug:
Mozilla bug #504184
I have a stripped down example at http://neolography.com/staging/shift-reload/shift-reload-testcase.html which I will leave up. I encourage all to vote for this bug in the mozilla bug tracker so that it will get fixed.
j

Categories

Resources