Assign Javascript image object directly to page - javascript

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;
}
}

Related

Image Swap on MouseOut (JavaScript, not JQ)

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]

Adding different images to a form according to name using if/else

I am trying to insert image values into the html to replace the src according to the name so if the name for the templateName = Javascript I can make the src value = something like say (http://www.w3devcampus.com/wp-content/uploads/logoAndOther/logo_JavaScript.png) and do that for other categories as well using an if/else statement in javascript.
my script look like this but it has a few errors with the syntax
var imageChoosernator = function () {
if (#templateName == "Javascript")
{
img = <img src="htp://www.w3devcampus.com/wp-content/uploads/logoAndOther/logo_JavaScript.png">;
}
` }
Can someone guide me toward the proper solution?
# in #templateName is wrong. Know your allowed variable characters.
img = <img the <img is an unstarted String. Know how to enclose values into String.
` <<< you cannot have such character floating around your code (hopefully just an edit typo).
Since you didn't showed most of your code, a fix would be something like:
var img = "";
var templateName = "Javascript";
function imageChoosernator () {
if (templateName === "Javascript") { // remove unallowed #
img = '<img src="js.png">'; // enclose into String
} else {
img = '<img src="someting.png">';
}
// Finally append img to element #imgContainer
document.querySelector("#imgContainer").insertAdjacentHTML("beforeend", img );
}
imageChoosernator(); // Do the magic
You can use jQuery .prepend() method to replace the image src on loading the query into the page.
If in html you have given the id name as 'JavaScript' like-
div id="JavaScript"><img id="imgNew1" src="oldImg1.png" />
div id="templateName2"><img id="imgNew2" src="oldImg2.png" />
To change the image source following can be used-
$('#templateName1').prepend('<img id="imgNew" src="newImg1.png" />')
$('#templateName2').prepend('<img id="imgNew" src="newImg2.png" />')
You need to read the documentation here
To automatize the src change while creating intances of the same will go like-
<html>
<head>
<script type="text/javascript">
var slideimages = new Array() // create new array to preload images
slideimages[0] = new Image() // create new instance of image object
slideimages[0].src = "firstImg.png" // set image object src property to an image's src, preloading that image in the process
slideimages[1] = new Image()
slideimages[1].src = "secondcarImg.png"
slideimages[2] = new Image()
slideimages[2].src = "thirdImg.png"
</script>
</head>
<body>
<img src="firstImg.img" id="slide" width=100 height=56 />
<script type="text/javascript">
//variable that will increment through the images
var step = 0
var whichimage = 0
function slideit(){
//if browser does not support the image object, exit.
if (!document.images)
return
document.getElementById('slide').src = slideimages[step].src
whichimage = step
if (step<2)
step++
else
step=0
}
</script>
</body>
</html>

Assigning model value to JavaScript variable MVC 4

I am trying to make a image slide show and I am passing urls of the images through a List in a Model.
List<string>
Onload I want to assign these URL values to JavaScript variables.
var image1=new Image()
var image2=new Image()
var image3=new Image()
My question is, how can I assign this list of URLs to the above variables, normally I can do this:
image1.src="value.jpg"
How can assign the value using Razor within JavaScript?
This razor code will create an image object with the index for each element in your List of strings and will set its src property.
<script>
#for (var idx = 1; idx <= Model.ListOfImages.Length; ++ i) {
<text>
var image#(idx) = new Image();
image#(idx).src = '#Model.ListOfImages[idx]';
</text>
}
</script>
Of course you will want to wrap it in the script tag. The output will be JavaScript that looks something like this:
<script>
var image1 = new Image();
image1 = 'image1.jpeg';
var image2 = new Image();
image2 = 'image1.jpeg';
var image3 = new Image();
image3 = 'image1.jpeg';
</script>
A couple of ways to solve this:
Use Razor to generate JavaScript
<script type="text/javascript">
var images = [], image;
#foreach (var image in ListOfImages)
{
image = new Image();
image.src = #image.url;
images.push(image);
}
</script>
Use Razor to generate HTML, then have JavaScript use the HTML for the slideshow
<div class="slideshow">
<ol>
#foreach (var image in ListOfImages)
{
<li><img src="#image.url"></li>
}
</ol>
Prev
Next
</div>
<script type="text/javascript">
// some imaginary jQuery plugin to create a slideshow
$(".slideshow").slideshow();
</script>
I'm partial to solution #2. I try to avoid having a server side templating language generate code in more than one language if at all possible. In solution #2, Razor is just generating HTML.

Display image through html image element object

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)

how to load a picture from .js file to html?

I have a file called src.js which has all the scripts for my html page.
now on my html page I am using this :
<script language="javascript" src="src.js">
</script>
to call the .js file to use it.
I am not sure how to set up the images links in the .js file or how to call them in the .html file
I need a simple answer please :)
You need to have a placeholder for your images in the HTML otherwise you would need to dynamically modify the HTML DOM structure.
As for using variables for image links, refer to the code below which pre-loads the images.
if (document.images)
{
preload_image_object = new Image();
// set image url
image_url = new Array();
image_url[0] = "http://mydomain.com/image0.gif";
image_url[1] = "http://mydomain.com/image1.gif";
image_url[2] = "http://mydomain.com/image2.gif";
image_url[3] = "http://mydomain.com/image3.gif";
var i = 0;
for(i=0; i<=3; i++)
preload_image_object.src = image_url[i];
}
The browser must have the document.images attribute defined.
<div id="_images"></div>
<script>
var images = { // images with properties
image1 : {url:'http://image1',property:'value'},
image2 : {url:'http://image2',props:[],else:'val'}
}
for(var i in images){
var image = new Image();
image.src = images[i].url;
// put image anywhere you want
document.getElementById('_images').appendChild(image)
}
</script>

Categories

Resources