Image Swap on MouseOut (JavaScript, not JQ) - javascript

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]

Related

Hide img when alternate image not exists

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)'>

Removing current image before loading a new one JavaScript

I load an image from URL by using document.createElement('img'). And a button triggers it. But, every time I click the button, it creates another img element instead of removing the current one. Can you help me to remove the current image so that there is always maximum one image displayed. Here is the code:
<script>
function() {
var imageUrl = document.getElementById('image-url').value;
var loadedImage = document.createElement('img');
loadedImage.src = imageUrl;
loadedImage.className = 'container';
document.getElementById('imagePlace').appendChild(loadedImage);
}
</script>
Every time you call appendChild method, you add a node to your document, so some changes to your code are required - you should check if the image node is already present and either create a new img element or replace the src attribute of the existing one.
<script>
function() {
// Get a new image url
var imageUrl = document.getElementById('image-url').value;
// Get a parent element
var parent = document.getElementById('imagePlace');
// Try to get an 'img' element that is inside '#imagePlace' node.
var currentImage = parent.querySelector('img');
// Check if there already is an image in the document.
if (currentImage) {
// If there is, replace its 'src' attribute with the new url.
currentImage.src = imageUrl;
}
else {
// If there is no image in the parent, create and add new image node.
var loadedImage = document.createElement('img');
loadedImage.src = imageUrl;
loadedImage.className = 'container';
parent.appendChild(loadedImage);
}
}
</script>
In other approach you may start with removing the img node if it's present in the #imagePlace container, however changing the src attribute is "cheaper" to perform.
<script>
function() {
// Get a new image url
var imageUrl = document.getElementById('image-url').value;
// Get a parent element
var parent = document.getElementById('imagePlace');
// Try to get an 'img' element that is inside '#imagePlace' node.
var currentImage = parent.querySelector('img');
// Check if there already is an image in the document.
if (currentImage) {
// If it's there, remove it.
currentImage.remove();
}
// Create and add new image node.
var loadedImage = document.createElement('img');
loadedImage.src = imageUrl;
loadedImage.className = 'container';
parent.appendChild(loadedImage);
}
</script>

How to display an array of images as a list and make them clickable to display some text using javascript?

I need to display a list of images from an array and also make it clickable to display some text on click. Looking for some simple solution only with javascript.
var images = ["img1", "img2", "img3"];
var allPics = images.length;
var i = 0;
for(;i<allPics; i++){
myImg.src = images[i];
}
Example here:
https://jsfiddle.net/gmqLtd1u/1/
Now only one image is displayed.
Now only one image is displayed.
Because you're using one <img> and update its src several times in loop. After last iteration, its src is not updated anymore. That's why you see the last image.
Change your html, so that instead of <img> you have <div> as container/placeholder:
<!-- <img id="myImg"/> -->
<div id="myImg"></div>
And change your JS, to create <img> and append it to <div>:
for(;i<allPics; i++){
// myImg.src = images[i];
// TODO: adjust this to whatever you want
// in this example, use `<a>` that link to another page
// you can use javascript to show modal/alert too
var a = document.createElement('a');
a.href = 'example.html'; // TODO: adjust this
var img = document.createElement('img');
img.src = images[i];
a.appendChild(img);
document.getElementById('myImg').appendChild(a);
}
And maybe your CSS, to match with new output:
#myImg img {
...
}

I have created image tag in JavaScript, but it is not displaying image on web page

I am calling this function on add button from my PHTML. On click of add button I want to show image of selected fruit in <div>.
function moveoutid()
{
var sda = document.getElementById('availableFruits');
var len = sda.length;
var sda1 = document.getElementById('orderFruits');
for(var j=0; j<len; j++)
{
if(sda[j].selected)
{
alert(baseUrl+"/img/"+sda.options[j].value+".jpg");
var img1=document.createElement('img').src=baseUrl+"/img/"+sda.options[j].value+".jpg";
var di=document.getElementById('d');
di.appendChild(img1);
var tmp = sda.options[j].text;
var tmp1 = sda.options[j].value;
sda.remove(j);
j--;
var y=document.createElement('option');
y.text=tmp1;
try
{
sda1.add(y,null);
}
catch(ex)
{
sda1.add(y);
}
}
}
}
In this code I have created <img> tag and passing image path to src, to show selected image on web page. It is correctly taking path of images but it is not appending <img> tag and not displaying image on web page.
Your problem is, most likely, in this line:
var img1=document.createElement('img').src=baseUrl+"/img/"+sda.options[j].value+".jpg";
This creates an element, assigns the src property to it and then assigns the value of this src property to variable img1. Instead, you should do this in two lines:
var img1 = document.createElement('img');
img1.src = baseUrl+"/img/"+sda.options[j].value+".jpg";

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)

Categories

Resources