The image replace function works for one swap ,but it does not works for another swap.
i have used complete paths for images in my code.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Can Change Images</h1>
<img id="myImage" onclick="changeImage()" src="file://C:/Users/dell/Desktop/asd.png" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("file://C:/Users/dell/Desktop/Capture.png")) {
image.src = "file://C:/Users/dell/Desktop/asd.png";
} else {
image.src = "file://C:/Users/dell/Desktop/Capture.png";
}
}
</script>
</body>
</html>
getAttribute() returns exactly what was in the HTML. It may be a relative URL.
.src returns a fully qualified absolute URL, even if what was in the HTML was a relative URL.
img.src will return values like file:///C:/Users/dell/Desktop/asd.png hence condition fails.
Try this:
function changeImage() {
var image = document.getElementById('myImage');
if (image.getAttribute('src').match("file://C:/Users/dell/Desktop/Capture.png")) {
image.src = "file://C:/Users/dell/Desktop/asd.png";
} else {
image.src = "file://C:/Users/dell/Desktop/Capture.png";
}
}
<h1>JavaScript Can Change Images</h1>
<img id="myImage" onclick="changeImage()" src="file://C:/Users/dell/Desktop/asd.png" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
You are doing two different things one is u are using a html document where u are calling a file and another is image so instead of using any other javascript events u can use file:///path
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("file:///C:/Users/dell/Desktop/Capture.png")) {
image.src = "file:///C:/Users/dell/Desktop/asd.png";
} else {
image.src = "file:///C:/Users/dell/Desktop/Capture.png";
}
}
</script>
Related
I am attempting to make it so that when you drag an image from your files or the internet into the drop area it makes an image on the page take the SRC of that image. This seems like it would be easy, but I have looked all over the internet
and have been unable to figure this out. Chrome throws the error:
'No function was found that matched the signature provided'.
<!doctype html>
<html>
<head>
<script>
function dropHandler(ev) {
ev.preventDefault();
img = new Image();
fileTransferred = ev.dataTransfer.items[0];
img.src = window.URL.createObjectURL(ev.dataTransfer.items[0]);
ev.dataTransfer.items.clear();
ev.dataTransfer.clearData();
window.URL.revokeObjectURL(img.src);
}
function dragOverHandler(ev) {
ev.preventDefault();
}
</script>
</head>
<body>
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
<p>Drag a picture here.</p>
</div>
</body>
</html>
Why doesn't this work?
After a bit of checking, I found out that you should make it behave as a file, not an item. Demo that shows this is here.
JS
function dropHandler(ev) {
ev.preventDefault();
img = new Image();
fileTransferred = ev.dataTransfer.files[0];
img.src = window.URL.createObjectURL(fileTransferred);
ev.dataTransfer.items.clear();
ev.dataTransfer.clearData();
window.URL.revokeObjectURL(img.src);
alert(img.src);
}
function dragOverHandler(ev) {
ev.preventDefault();
}
I want to show a low-res image and start loading the hi-res image after the complete page has rendered. Only when the hi-res image is completely loaded, I want to replace the low-res image by the hi-res image.
I know I should use
$(window).load(function(){
});
But what do I do to actually start loading a certain image? And how do I know when the image is loaded?
(I know about the existence of lazyload, but this image has to be the background of an element, so I have to use .css("background-image", var) and can't use lazyload I guess.)
Use this script to preload the images:
<div class="hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"images-1.png",
"images-2.png",
"images-3.png",
"images-4.png"
)
//--><!]]>
</script>
</div>
Then use low-res images in your html as you need and change to hi-res images when needed. The preloaded image is there for you.
$(window).load(function(){
$(selector).css('background-image',images[0]);
});
In your HTML
<img src='lowres.gif id='mypic'>
<script>
var img = document.getElementById("mypic");
var img2 = new Image();
var img2.onload = function() {
img.parent.insertBefore(img2, img);
// Or hide it.
img.style.display = "none";
};
var img2.src = XXXXX;
</script>
I have this code im using on my website but the image does not load when page opens, I want the image to load from start up then a simple mouse over to change image and a link when clicked. Im not good at coding so any help would be good.
here is the code im using.
<!doctype html>
<html>
<body>
<head>
<script>
function init() {
setImageOne();
}
function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }
function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.src = src;
context.drawImage(img, 0, 0, 322, 200);
}
</script>
</head>
No Canvas Support in Browser
You need to wait for the image to load before you draw it. Also, if your browser doesn't support canvas nothing will help you with this approach.
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0, 322, 200);
};
img.src = src;
}
You should wait for the image to load. Thus your code should be (with corrections regarding html markup):
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="e" style="width: 100%; height: 100%;"></canvas>
<script>
function init() {
setImageOne();
}
function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }
function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image;
img.onload = function (){
context.drawImage(img, 10, 10);
};
img.src = src;
}
init();
</script>
</body>
</html>
This only works in browsers that support canvas ex: Chrome(ium)
Also I suggest you read this
Is this the first method you tried? If you are just trying to add an image on a website and a hover over it there is a much simpler way.
First off, instead of using Javascript to create and load an Image, use the HTML <img> tag, example:
<img src="http://earthbounds.com/banners/amazing food.jpg">
Now to add a simple hover image change, this is not the best practice but for an example, and for a single image you can use onmouseover and onmouseout, example:
<img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')">
Now to make this image a link to another page, or website you use the <a> tag, example:
<img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')">
Hope this helps, and keep looking and learning!
I wanted to implement a swapImage on my site that would swap one image on mouseover, and another image on mouseout. Essentially, with the solution I found I could also probably swap different images for mousedown and mouseup even.
I have this happening in 8 different nested tabs, all of which are on the same page.
The javascript looks like this:
<script type="text/javascript">
function swapImageFiat(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function swapImageHarley(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function swapImageHotWheels(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function swapImageVoltron(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function swapImageBenchmade(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function swapImageCrew(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function swapImageReuters(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function swapImageMarsVolta(imgID, imgSrc) {
var theImage = document.getElementById(imgID)
theImage.src = imgSrc;
}
function preLoadImages() {
for(var i = 0; i < arguments.length; i++) {
var theImage = new Image();
theImage.src = arguments[i];
}
}
</script>
And the inline code for each image would be essentially this:
<img class="diagram" src="img/fiat.gif" id="imgToSwapFiat" alt="Diagram" data-title="Fiat Diagram" onClick="swapImageFiat('imgToSwapFiat', 'img/fiat-animated.gif')" onmouseout="swapImageFiat('imgToSwapFiat', 'fiat.gif')" height="189" width="358" />
I would like to be able to use less IDs, less of the same repetitive script, and shorter inline code.
But I also want the flexibility of being able to just change the images and their IDs, rather than fussing with JQuery or other script. This is why I'm using getElementById.
Is there a more efficient way for me to write that JavaScript, and/or Inline code?
Also
Is there a way for the image to swap back to the original after the animation stops playing, rather than on mouse-out?
Use this instead of the element ID since your function eventually need the actual element object.
The script example:
function swapImageFiat(imgEle, imgSrc) {
imgEle.src = imgSrc;
}
The image HTML example:
<img src="initial.jpg" onclick="swapImageFiat(this, 'clicked.jpg')" onmouseover="swapImageFiat(this, 'hovered.jpg')" onmouseout="swapImageFiat(this, 'left.jpg')" />
Yeah, sure there is. As Jan mentions - all of your functions are identical. There's no need to duplicate them all. Also, you can remove the inline event-handler code from your html, simply attaching the mouseover/mouseout or mousedown/mouseup.
Simply add a new attribute to each image that you wish to have the effect for, then runs some js on page-load to attach the handler.
Here, I've just used (and checked for the existance of) custom attributes. If the image has them, I attach handlers. If not, it's no different to any other normal image. This should be nice an re-usable and little effort to use.
As for resetting the image once the animated gif has played, I'd probably look at Jan's first suggestion. A slight modification on the idea would be to make the last frame transparent, then simply position the animated image over (z-index higher) the static one.
When it's done, you'll see the original image again. You'll have to decide on a system for refreshing these images, should they need to be re-played. I'm not sure, perhaps setting their src to '', before setting it back to the animated.gif would cause the animation to play from the start again - you'd have to check if to decided to attempt such an approach.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function mInit()
{
var imgList = document.getElementsByTagName('img');
var i, n = imgList.length;
for (i=0; i<n; i++)
{
if (imgList[i].hasAttribute('img2'))
imgList[i].addEventListener('click', imgClick, false);
if (imgList[i].hasAttribute('img3'))
imgList[i].addEventListener('mouseover', imgHover, false);
if (imgList[i].hasAttribute('img4'))
imgList[i].addEventListener('mouseout', imgOut, false);
}
}
// because these function are attached with addEventListener, the 'this'
// keyword refers to the image element itself. No need for IDs..
function imgClick()
{
this.src = this.getAttribute('img2');
}
function imgHover()
{
this.src = this.getAttribute('img3');
}
function imgOut()
{
this.src = this.getAttribute('img4');
}
window.addEventListener('load', mInit, false);
</script>
<style>
</style>
</head>
<body>
<img src='img/gladiators.png'> <!-- this image won't be touched, as it doesn't have img1, img2 or img3 attributes -->
<img src='img/opera.svg' img2='img/chromeEyes.svg' img3='img/rss16.png' img4='img/girl2.png'/>
</body>
</html>
Jay has a good suggestion for your functions, which all do the same thing. If you remove the names from your functions you'll see they are otherwise identical. And the function name makes no difference at all, in this case it's just the arguments you pass to the function that matters.
Is there a way for the image to swap back to the original after the
animation stops playing, rather than on mouse-out?
You could make the gifs non-looping and make the last frame of the animation the same as the original image. AFAIK there's no way to detect which frame an animated gif is on through Javascript.
If you really want it to return to the original image, you could animate the image completely through Javascript: Write a function that preloads all the images (or a spritemap) and then load them frame by frame.
<script>
function start(){
sprites.start();
preloader();
}
</script>
I am having two functions one to preload and other to load the image. Both functions running succesfully but what i want is stop preload function to execute and shows the next function when ever image loading is done.
Briefly i want to hide the preload function and show the sprite function after loading of sprite function
Take a look at this:
Wait for image to be loaded before going on
Here is a simple mockup:
<html>
<head>
<script language="javascript">
function loadImage()
{
var img = new Image();
img.src = 'img_navsprites.gif';
console.log( '1. Image has just started downloading.' );
document.getElementsByTagName('body')[0].appendChild(img);
img.onload = function() {
console.log( '2. Image has fully loaded.' );
}
console.log( '3. Hey, look at me ... all the way down here!' );
}
</script>
</head>
<body onload="loadImage()">
<div>
</div>
</body>
</html>
And a another mockup at PasteBin based on your code:
http://pastebin.com/wcBY2YaL