Look at this script please
var src="some.jpg";
var img = new Image();
img.src = src;
img.id = "crop_image";
$("#crop_image").load(function()
{
$("#crop_cont").append(img);
})
why in my .load function i can't access to img element?
Thanks much
UPDATE:
But the following works
$('<img src="'+src+'" />').load(function()
{
var img = new Image();
img.src = src;
$("#crop_cont").append(img);
})
Neither of those two examples really make any sense.
In the first, you create an Image but you don't add it to the DOM. Thus, when you ask jQuery to go find it, it can't because it's not there yet.
In the second, you create a new image tag, which (internally) is going to give jQuery an actual DOM element to work with. However, that call to append your Image object to the DOM seems superfluous. You've already got an <img> so there's no need for another one.
I'd change the second one as follows:
$('<img src="'+src+'" />').load(function() {
$("#crop_cont").append(this);
});
$("#crop_image") will not find your new image because you haven't added it to the DOM yet. Use $(img) instead.
A correct way to do it would be:
var src="some.jpg";
var img = new Image();
img.src = src;
img.id = "crop_image";
$(img).load(function(){
$("#crop_cont").append(this);
});
#crop_image, does it actually get appended to the doc? if so when?
you need to provide html to that.right
<img src="" />
Otherwise how can it display
image has it's own onload event, it's probably easiest to do something like this
var src="some.jpg";
var img = new Image();
img.id = "crop_image";
img.onload = $("#crop_cont").append(img); // event added
img.src = src;
edit: err, I mean the Image Object.
Related
In asp.net img tag I need to set gif image. I set gif image for src of the img and if gif doesn't exist I need to set jpg for the img. But if the jpg also not exists I need to hide the img from the page.
I used onerror event of the img tag for this with the javascript function. But at sometimes it saying the function not found.
Is there ay easy way to do this. My need is to set gif to img and if the gif not exists set jpg to it and if jpg also not exists need to hide the img.
I tried like this
<img src="mygif.gif" onerror="setJpg($(this));">
function setJpg(source) {
var file = source[0].src;
var jpgFile = file.substr(0, file.lastIndexOf(".")) + ".jpg";
var img = document.createElement('img');// new Image();
img.onload = function () { source[0].src = jpgFile; };
img.onerror = function () { source.parent().hide() };
img.src = jpgFile;
}
The onerror event eventually gets recalled after changing the src of the image. So you do not have to create another img and can resue the same event. Like set a new handler or check for the ending.
//REM: Note that "img" is an element and not jquery wrapped.
function setJpg(img){
console.log('Called onerror');
//REM: If image ends with ".gif"
if(img.src.toLowerCase().endsWith('.gif')){
//REM: Change ".gif" to ".jpg", whatever your logic is.
//REM: This is going to call onerror again if not found
img.src = img.src.replace('.gif', '.jpg');
console.log('Changed src', img.src)
}
else{
//REM: Remove the event
img.onerror = null;
//REM: Remove the image or do whatever you want with it
img.remove();
console.log('Removed element')
}
}
<img src = 'wayne.gif' onerror = 'setJpg(this)'>
I am trying to create functions to mouseover and mouseout of images. The tricky part is this function needs to work for any image, and I cannot use direct image names. I have to therefore use variables.
The HTML code is as follows for the images:
The HTML for the images is like this, and there are 3 images:
<img src="images/h1.jpg" alt="" id="images/h4.jpg" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I'm expecting that you have to reference the id for the new image, and then the src attribute for the previous image to revert when you mouseout.
The problem is that, if I reference the id attribute, the image no longer has information on the src attribute so I cannot call it to revert back.
Here is the JavaScript I have thus far. It works to swap the image to a new one, but not to swap it back :(
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var ulTree = $("image_rollovers");
var imgElements = ulTree.getElementsByTagName("img");
//PROCESS EACH IMAGE
//1. GET IMG TAG
for (var i = 0; i < imgElements.length; i++) {
console.log (imgElements[i]);
console.log (imgElements[i].getAttribute("src"));
//2. PRELOAD IMAGE FROM IMG TAG
var image = new Image();
image.setAttribute("src", imgElements[i].getAttribute("src"));
//3. Mouseover and Mouseout Functions Called
image.addEventListener("mouseover", swapToNewImage);
image.addEventListener("mouseout", swapImageBack);
}
}
//MOUSE EVENT FUNCTIONS
var swapToNewImage = function(img) {
var secondImage = img.getAttribute("id", "src");
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.getAttribute("src");
img.src = previousImage;
}
Let me know if you can help me figure out how to call the image's src attribute so it can be reverted back. Again, I cannot reference specific image names, because that would be a lot easier (: Thank you!
Well, You can use a data attribute to store your src, and a data attribute to store the image you want to swap when mouseover.
Please try the following example.
var swapToNewImage = function(img) {
var secondImage = img.dataset.swapSrc
img.src = secondImage;
}
var swapImageBack = function(img) {
var previousImage = img.dataset.src
img.src = previousImage;
}
<img src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="" data-src="https://images.pexels.com/photos/259803/pexels-photo-259803.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" data-swap-src="https://images.pexels.com/photos/416160/pexels-photo-416160.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" onmouseover="swapToNewImage(this)" onmouseout="swapImageBack(this)">
I also notice that the image tag is generated by code, in order to set the dataset values, we can do this:
var image = new Image();
image.scr = [src]
image.dataset.src = [src]
image.dataset.swapSrc = [swap src]
Within an object constructor there's a method named addToViewport(), which has the role of simply displaying an image after preloading it:
window.onload = function(){
function ViewportObject(){
this.src = "https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=asdasdasd&choe=UTF-8&chld=L|0";
this.addToViewport = function(){
// Determine the DOM object type to create
var DOM_elem = "img",
obj = $(document.createElement(DOM_elem)),
img = new Object();
obj.addClass("object");
obj.css({"z-index":"100","width":"300px","height":"auto"});
// Preload the image before rendering it and computing its size
img.src = this.src;
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
}
}
var o = new ViewportObject();
o.addToViewport();
}
The problem I've come across is that the script doesn't enter the "onload" event handler block, so the image doesn't get displayed.
I put together a web page with the same script as above on http://picselbocs.com/test/ for you to check out live.
What is it that I'm doing wrong here?
Try this:
change this
img = new Object();
....
img.src = this.src;
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
to
img = new Image();
....
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
img.src = this.src;
I have the following code :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
}
pastedImage.src = source;
}
The function createImage contain the source parameter which contain the source of an image. After that I created the object pastedImage of class Image and after alerting that I am getting the html image element object like [object HTMLImageElement].
My question is how I can display image into my html page using that object. I want to display it after onload function.
Hiya : Working demo http://jsfiddle.net/wXV3u/
Api used = .html http://api.jquery.com/html/
In demo click on the click me button.
Hope this helps! Please lemme know if I missed anything! B-)
Code
$('#foo').click(function() {
createImage("http://images.wikia.com/maditsmadfunny/images/5/54/Hulk-from-the-movie.jpg");
});
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
}
pastedImage.src = source;
$(".testimonialhulk").html(pastedImage);
}
Also you can do like this :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Your image in canvas: <img src="'+pastedImage.src+'" height="100" width="200"/>');
}
pastedImage.src = source;
}
Simple, and better, using javascript dom primitive (replaceChild):
Get the parent of the image, the div or span that contains it, and replace the old img tag with the new image object you created with your function
var domImgObj = document.getElementById("image");
var imgObj = createImage(src); // your function
imgObj.id = pageimgObj.id; // necessary for future swap-outs
document.getElementById("container").replaceChild(imgObj,domImgObj);
document.createRange().createContextualFragment(img.outerHTML)
Example
const img = new Image()
img.src = "https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico"
const frag = document.createRange().createContextualFragment(`${img.outerHTML}`)
document.querySelector(`body`).append(frag)
Is it possible to assign a Javascript image object directly to the DOM? Every example I've seen has the image object being loaded and then the same file name assigned to an HTML element and my understanding is that the actual image data is coming from the browser cache in the filing system.
I want to guarantee that the image is loaded so I want to load it into a Javascript image object have the data in memory and then add it directly to the page.
Is this possible?
Cheers, Ian.
You can create the image element and append it directly to the DOM once it has loaded:
var image = new Image();
image.onload = function(){
document.body.appendChild(image);
};
image.src = 'http://www.google.com/logos/2011/guitar11-hp-sprite.png';
example: http://jsfiddle.net/H2k5W/3/
See:
<html>
<head>
<script language = "JavaScript">
function preloader()
{
heavyImage = new Image();
heavyImage.src = "heavyimagefile.jpg";
}
</script>
</head>
<body onLoad="javascript:preloader()">
<a href="#" onMouseOver="javascript:document.img01.src='heavyimagefile.jpg'">
<img name="img01" src="justanotherfile.jpg"></a>
</body>
</html>
Reference:
http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317
if (document.images) {
var preload_image_object = new Image();
var image_urls = new Array();
image_urls[0] = "http://mydomain.com/image0.gif";
image_urls[1] = "http://mydomain.com/image1.gif";
image_urls[2] = "http://mydomain.com/image2.gif";
image_urls[3] = "http://mydomain.com/image3.gif";
var i = 0;
for(image_url in image_urls) {
preload_image_object.src = image_url;
}
}