I have some javascript code that creates an img tag with a mouseover callback, and adds the img tag to the page. The problem is that a javascript syntax error happens (in the Firefox Console) whenever the callback is invoked.
This code demonstrates the problem...
var imgUrl = 'http://sstatic.net/so/img/logo.png';
var img = document.createElement('img');
img.setAttribute('src', imgUrl);
img.setAttribute('onmouseover', function() {
alert('mouseover ' + imgUrl);
});
document.body.appendChild(img);
The syntax error even happens when the callback function is an empty function.
Can anyone explain what's causing the syntax error and how to fix it?
(I'm using FF 3.5.2 on Win XP.)
You're passing in a function where a string is expected. Try this instead:
var imgUrl = 'http://sstatic.net/so/img/logo.png';
var img = document.createElement('img');
img.src = imgUrl;
img.onmouseover = function() {
alert('mouseover ' + imgUrl);
};
document.body.appendChild(img);
Related
The code below works perfectly in browser, but not in Electron env.
function listenFileInput() {
fileInput.addEventListener('change', ev => {
startProgress();
const file = ev.target.files[0];
if (!file) return clearProgress();
loadImage(file);
});
}
function loadImage(file) {
const image = new Image();
image.onload = function() {
const src = cropImage(this);
cardImage.src = src;
clearProgress();
};
image.src = window.URL.createObjectURL(file);
}
function startProgress() {
fileBtn.setAttribute('disabled', true);
fileInput.setAttribute('disabled', true);
progress.style.display = 'flex';
}
function clearProgress() {
fileBtn.removeAttribute('disabled');
fileInput.removeAttribute('disabled');
progress.style.display = 'none';
}
In Electron env, when the file is loaded, the progress doesn't show up.
After do some tests, I found some interesting phenomenon:
If I comment the image.onload = function() {...} block, it works properly.
If I add alert() in onChange event callback or startProgress function, after alerting, the progress appears as expected.
If I comment clearProgress(); in image.onload callback, after the image was loaded, the progress appears.
So, it seems that the setAttribute and style.display didn't work (or Electron didn't re-render the page) until the image was loaded, unless there's an alert disturbs the process.
I've pushed the complete code to GitHub (/lib/file.js).
I'm looking to dynamically load in an image:
<img data-src="test01">
And then use jQuery to take the data-src and then load in the image associated with that name, PLUS the extension. If THAT extension fails, then move onto the next extension, so on and so on until we get to the bottom when I just load in a default image. But I don't know how to check if there's an error AFTER I've set the image's attr once. Here's the loop I have so far, and I'm getting ".error not a function"
$("img").each(function(){
var newSource = $(this).data('src').toString();
$(this).attr('src', 'images/'+newSource+'.gif').error(function(){
$(this).attr('src', 'images/'+newSource+'.jpg').error(function(){
$(this).attr('src', 'images/'+newSource+'.png').error(function(){
$(this).attr('src', 'images/default.jpg');
});
});
});
});
The reason I'm doing this is because we have a database that holds the title of the image only, yet, over the years, different people have uploaded different image formats to the site, and we want to be able to load all of them on the page, sans extension, and then loop through each extension until we find a file that exists, and if not, default to a pre-set hard coded image URL
One alternative would be to do a HEAD request for the urls. A benefit of a HEAD request is that it just tries to get headers for the endpoint, without trying to return data, so it can be super fast. In your case, it could be a quick check to see if an image url is valid or not.
function changeTheSrcIfTheUrlIsValid ( element, url ) {
return $.ajax({
url: url,
type: 'HEAD',
success: function(){
//got a success response, set the src
element.src = url;
}
});
}
$("img").each(function(){
var img = this;
var newSource = img.getAttribute('src');
//check for a gif
changeTheSrcIfTheUrlIsValid( img, 'images/'+ newSource +'.gif' )
.then(null, function(){
//error handler, try jpg next
changeTheSrcIfTheUrlIsValid( img, 'images/'+ newSource +'.jpg' )
.then(null, function(){
//error handler, try png next
changeTheSrcIfTheUrlIsValid( img, 'images/'+ newSource +'.png' )
.then(null, function(){
//error handler, use default
img.src = 'images/default.jpg';
});
});
});
});
Can use a Promise and a new Image() each time. The promise gets resolved or rejected in the onload or onerror of the new Image.
Then there is a chain of catch() to try various extensions and finally set a default noImageUrl if all else fail
Something like:
function setImageSrc(src, ext, el){
return new Promise(resolve, reject){
var url = 'images/'+src+ ext;
var img = new Image()
img.src = url
img.onerror = reject;
img.onload = function(){
el.src = url; // set src of current element in dom
resolve(url)
}
}
}
$("img").each(function(){
var newSource = $(this).data('src').toString();
var self = this
setImageSrc(newSource, '.jpg', self)
.catch(setImageSrc(newSource, '.png', self))
.catch(setImageSrc(newSource, '.gif', self))
.catch(function(){
self.src = 'noImageUrl';
});
});
I want to create an alert box after an image is loaded, but if the image is saved in the browser cache, the .onload event will not be fired.
How do I trigger an alert when an image has been loaded regardless of whether the image has been cached or not?
var img = new Image();
img.src = "img.jpg";
img.onload = function () {
alert("image is loaded");
}
As you're generating the image dynamically, set the onload property before the src.
var img = new Image();
img.onload = function () {
alert("image is loaded");
}
img.src = "img.jpg";
Fiddle - tested on latest Firefox and Chrome releases.
You can also use the answer in this post, which I adapted for a single dynamically generated image:
var img = new Image();
// 'load' event
$(img).on('load', function() {
alert("image is loaded");
});
img.src = "img.jpg";
Fiddle
If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete also.
code sample:
$("img").one("load", function() {
//do stuff
}).each(function() {
if(this.complete || /*for IE 10-*/ $(this).height() > 0)
$(this).load();
});
There are two possible solutions for these kind of situations:
Use the solution suggested on this post
Add a unique suffix to the image src to force browser downloading it again, like this:
var img = new Image();
img.src = "img.jpg?_="+(new Date().getTime());
img.onload = function () {
alert("image is loaded");
}
In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again
I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {}) instead of document.ready would solve part of issue (if you are not ajaxing the page).
I found that you can just do this in Chrome:
$('.onload-fadein').each(function (k, v) {
v.onload = function () {
$(this).animate({opacity: 1}, 2000);
};
v.src = v.src;
});
Setting the .src to itself will trigger the onload event.
I'm playing with file upload, drag and drop, and canvas, but for some reason the ondrop function never seems to run, here's the fiddle I'm working in: http://jsfiddle.net/JKirchartz/E4yRv/
the relevant code is :
canvas.ondrop = function(e) {
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function(event) {
var img = new Image(),
imgStr = event.target.result;
state.innerHTML += ' Image Uploaded: <a href="' +
imgStr + '" target="_blank">view image</a><br />';
img.src = event.target.result;
img.onload = function(event) {
context.height = canvas.height = this.height;
context.width = canvas.width = this.width;
context.drawImage(this, 0, 0);
state.innerHTML += ' Canvas Loaded: view canvas<br />';
};
};
reader.readAsDataURL(file);
return false;
};
why doesn't this event fire? I've tried it in firefox and chrome.
In order to get the drop event to fire at all you need to have an ondragover function:
canvas.ondragover = function(e) {
e.preventDefault();
return false;
};
If you try to drag your cat picture into the canvas it'll still not work, this error is reported in the Firefox console:
[04:16:42.298] uncaught exception: [Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMFileReader.readAsDataURL]" nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)" location: "JS frame :: http://fiddle.jshell.net/_display/ :: <TOP_LEVEL> :: line 57" data: no]
However it will work if you drag an image from your desktop. I think for images in the page you should use regular DOM access methods, the File API is only needed for external files dragged into the browser.
As far as I can tell, robertc's answer is how browsers continue to behave, you have to have an ondragover function set.
But to expand on it slightly, the function must return false and not true or undefined-- no-op functions will return undefined. It doesn't seem to matter whether you prevent default, the ondrop event handler will trigger. You will want a preventDefault in the ondrop function, otherwise the file will be immediately downloaded to your browser's default download folder:
document.getElementById('drop-zone').ondragover = function(e) {
return false;
}
document.getElementById('drop-zone').ondrop = function(e) {
e.preventDefault();
console.log('ondrop', e);
}
#drop-zone {
border: solid;
height: 3em;
width: 10em;
}
<div id="drop-zone">Drop zone</div>
I am trying to load an image from a url to check internet connectivity. When no internet connection, it should display a dojo warning dialog. This works for Firefox but does not for IE8.
Following is the code snippet:
var img = new Image();
img.src = userGuideUrl1_img + '?' + (new Date).getTime();
img.onload = function() {
window.open(userGuideUrl1);
}
img.onerror = function() {
dojo.addOnLoad(warningDialogFunc);
}
Here warningDialogFunc is a dojo object. Any thoughts?
Thanks
Could it be that the page is already loaded by the time the img.onerror handler is executed, and IE doesn't rexecute the function for the dojo.addOnLoad(warningDialogFunc)?
Try changing
img.onerror = function() {
dojo.addOnLoad(warningDialogFunc);
}
to simply:
img.onerror = function() {
warningDialogFunc();
}
You have to set up the handler before you set the source of image, when you change the src attribute, IE will try to download the image and trigger the events.
var img = new Image();
img.onload = function() {
window.open(userGuideUrl1);
}
img.onerror = function() {
dojo.addOnLoad(warningDialogFunc);
}
img.src = userGuideUrl1_img + '?' + (new Date).getTime(); // Trigger image download and the handlers.