Add Delay to Mouseover using Javascript - javascript

I'm using the following script for all my image mouseovers:
loadImage1 = new Image();
loadImage1.src="1.jpg";
staticImage1 = new Image();
staticImage1.src="1-roll,jpg";
How can I simply add, say, a second or two delay before it executes the mouseover?
Thanks in advance for your help!
---UPDATE---
Thanks for the replies. Excuse my ignorance when it comes to Javascript. How can I include the timeout piece in the following script?
<SCRIPT LANGUAGE="JavaScript">
loadImage1 = new Image();
loadImage1.src="/wp-content/themes/Anna%20Rawson/images/1-blog.jpg";
staticImage1 = new Image();
staticImage1.src="/wp-content/themes/Anna%20Rawson/images/1-blog.jpg";
</script>
Do I wrap the timeout piece in it's own script tag? Thanks for the quick help!

You can use setTimeout(), an example:
var img1 = document.getElementById('my-img');
img1.onmouseover = function() {
setTimeout(function() {
this.src = 'my-img-2.png';
}, 1000); // 1000ms = 1s delay
};
First of all, your code have some mistakes:
Always write HTML tags in lowercase, not <SCRIPT> but <script>
The langauge attribute is not a valid attribute, use type="text/javascript" instead, or just remove it it isn't required.
And the Image object is not really making an image on the website. It preloads the image, so you can use it on your website without loading it. Like this example:
<img src="/img/my-first-img.png" onmouseover="this.src = '/img/heavy-img.png'">
<script>
var heavyImg = new Image();
heavyImg.src = '/img/heavy-img.png'; // preload the img
</script>
Because we preload the /img/heavy-img.png we can directly see the heavy-img if me mouse over the first-img. If we don't preload the img, it will be loaded when we mouse over.
Instead of using an onmouseover attribute we use the onmouseover event + callback in the JS file. Now we can add a delay:
<img src="/img/my-first-img.png" id="my-img">
<script>
var heavyImg = new Image();
heavyImg.src = '/img/heavy-img.png'; // preload the img
var myImg = document.getElementById('my-img'); // get the element with id="my-img" out of the DOM
// create a mouseover event
myImg.onmouseover = function() {
setTimeout(function() {
this.src = '/img/heavy-img.png' // load the img
}, 1000); // a delay of 1000ms = 1s
};
</script>

Related

Javascript - Loading images causes things to randomly be undefined

Well this is a strange one for me.
I'm moving my game from ASCII to tile graphics and I have a problem.
After setting up an image pre-loader I get errors telling me that various stuff is undefined.
Here is the image loading function:
function preload(){
characterImage = new Image();
characterImage.src = "images/character.png";
groundImage = new Image();
groundImage.src = "images/ground.png";
wallImage = new Image();
wallImage.src = "images/wall.png";
doorImage = new Image();
doorImage.src = "images/door.png";
windowImage = new Image();
windowImage.src = "images/window.png";
creatureImage = new Image();
creatureImage.src = "images/creature.png";
stairImage = new Image();
stairImage.src = "images/stairs.png";
nullImage = new Image();
nullImage.src = "images/null.png";
}
Other than that I did not touch anything other than
<body id="body" onload="preload();">
Anyone have any idea what's happening here?
EDIT: I've found the problem, it's that the images aren't loaded before the main script executes. duh.
Onload only fires after everything is loaded (including images)
- so preloading at that point seems.. silly?
Either simply add them to the HTML, and start the game in the onload event
OR
Execute the preload function in < head > and count the number of loaded images by adding:
imageX.onload = function(){ if (++number==total) startGame() }
to each of them (number=0 and total=7 being global variables)
This assumes nothing else needs to be loaded.. A combination may be needed..
<body onload="preload();" >
this means that when the body is loaded, the brower will executes the preload();

How to preload images

I'm trying to preload images on my web page. I've seen a lot of discussions about it and most of them suggest to create an Image object then edit the src attribute. However this doesn't work on the latest versions of Chrome and Firefox. The request is marked as "pending" until the image is actually shown on the page and then I can notice a little delay before the image to be shown. Even creating an actual img tag on the page (with display:none) doesn't work until the image is shown. And finally when I try the following code, only the last image of the loop is actually loaded
var img = document.getElementById('some_visible_image');
for(var i=1;i<5;i++)
for(var j=1;j<3;j++){
img.src = 'images/'+i+'_'+j+'_green.png';
img.src = 'images/'+i+'_'+j+'_orange.png';
img.src = 'images/'+i+'_'+j+'_red.png';
}
So how can I reduce the loading time of the images (without using large sprites)?
You need to create instance for every image
// redirect after all the images are preloaded
function redirect() {
location.href = "yourtargetpage.html";
}
// should solve the first-time-load problem
var loads = 0;
function loaded() {
// the total number of images needed to load
if(++loads==42) redirect();
}
// if all the images aren't loaded in 3 seconds, don't wait further
setTimeout(redirect, 3000);
for(var i=1;i<5;i++)
for(var j=1;j<3;j++){
var img = new Image();
img.src = 'images/'+i+'_'+j+'_green.png';
if(img.complete) loaded(); // if cached, onload isn't fired sometimes
else img.onload = loaded; // fires for the first time the page loads
}
or the src is overwritten before the image has a chance to load.
To show your images immediately after the first load, you may run this script on a different page, wait until every image
I found the solution, thanks to Jan TuroĊˆ's answer. Here is my code :
for(var i=1;i<=5;i++)
for(var j=1;j<=3;j++){
var img = new Image();
img.src = 'images/'+i+'_'+j+'_green.png';
var img = new Image();
img.src = 'images/'+i+'_'+j+'_orange.png';
var img = new Image();
img.src = 'images/'+i+'_'+j+'_red.png';
var img = new Image();
img.src = 'images/'+i+'_'+j+'_grey.png';
}
Try visibility:hidden; instead of display:none;

How can I change out an image using CamanJS?

I've got multiple images, and I'd like to load them each into a single <canvas> element at different points in time and then manipulate them using CamanJS. I can get the first image to appear like this:
Caman('#canvas-element', '/images/one.jpg');
But then when I subsequently try to update that same element using the following code, it does not work.
Caman('#canvas-element', '/images/two.jpg');
Is there some way to reset/clear/flush the canvas and load new image data into it, or do I really need to create separate <canvas> elements for each image I want to load? I'd prefer a single element because I don't want to eat up all the memory.
Remove the Caman attribute (data-caman-id) from the IMG or CANVAS element, change the image, and then re-render Caman.
document
.querySelector('#view_image')
.removeAttribute('data-caman-id');
const switch_img = '/to/dir/img.png';
Caman("#view_image", switch_img, function() {
this.render();
});
Hope followed code can help others who have same require.
function loadImage(source) {
var canvas = document.getElementById('image_id');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function() {
context.drawImage(image, 0, 0, 960, 600);
};
image.src = source;
}
function change_image(source) {
loadImage(source);
Caman('#image_id', source, function () {
this.reloadCanvasData();
this.exposure(-10);
this.brightness(5);
this.render();
});
}
Just figured this one out with a lot of trial and error and then a duh moment!
Instead of creating my canvas directly in my html, I created a container and then just did the following:
var retStr = "<canvas id=\"" + myName + "Canvas\"></canvas>";
document.getElementById('photoFilterCanvasContainer').innerHTML = retStr;
Caman("#" + myName + "Canvas", myUrl, function() {
this.render();
});
You want the canvas id to be unique each time you access the Caman function with a new image.

How synchronize more gif pictures?

Is there any way, how to synchronize gif animations? Problem is that if they have same timing, but are loaded in different time, it can looks strange. I don't know, for example by some javascript "refresh" or reload or something else...
GIF animations are not scriptable. The best you can do is load them via JavaScript, then insert them both into the DOM after they've loaded.
Something like this:
var img = new Image();
var imgCount = 0;
img.onload = loadCount;
img.src="....."
var img2 = new Image();
img2.onload = loadCount;
img2.src="....."
function loadCount() {
imgCount++;
if(imgCount==2) {
//insert IMG tags into DOM
}
}

Set an Image object as a div background image using javascript

I want to load 4 images from background showing a load bar to the client
and when the images will be downloaded i want to set them as background images to 4 div blocks.
I am looking for something like this.
var myImages = new Array();
for(var i = 0; i < 4; i++)
myImages[i] = new Image();
//load images using the src attribute
//and execute an on load event function where to do something like this.
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = myImage[index];
Is there any way to set a background image using an Image javascript object?
You can do something close to what you had. You don't set an image background to be an image object, but you can get the .src attribute from the image object and apply that to the backgroundImage. Once the image object has successfully loaded, the image will be cached by the browser so when you set the .src on any other object, the image will load quickly. You could use this type of code:
var imgSrcs = [...]; // array of URLs
var myImages = [], img;
for (var i = 0; i < 4; i++) {
img = new Image();
img.onload = function() {
// decide which object on the page to load this image into
// this part of the code is missing because you haven't explained how you
// want it to work
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = "url(" + this.src + ")";
};
img.src = imgSrcs[i];
myImages[i] = img;
}
The missing part of this code is deciding which objects on the page to load which image into when the image loads successfully as your example stood, you were just loading each one into the same page object as soon as they all loaded which probably isn't what you want. As I don't really know what you wanted and you didn't specify, I can't fill in that part of the code.
One thing to watch out for when using the .onload event with images is you have to set your .onload handler before you set the .src attribute. If you don't, you may miss the .onload event if the image is already cached (and thus it loads immediately).
This way, the image shows up instantly all in one once it's loaded rather than line by line.
function setBackgroundImage(){
imageIsLoaded(myURL).then(function(value) {
doc.querySelector("body > main").style.backgroundImage = "url(" + myURL + ")";
}
}
function imageIsLoaded(url){
return new Promise(function(resolve, reject){
var img = new Image();
try {
img.addEventListener('load', function() {
resolve (true);
}, false);
img.addEventListener('error', function() {
resolve (false);
}, false);
}
catch(error) {
resolve (false);
}
img.src = url;
});
}

Categories