Img src is undefined after addEventListener - javascript

I want to change a picture to a gif on mouse over, and revert it back on mouse out. But img src stays undefined after onmouseout, howerer it should be visible, because imgsrc array is an global varriable
Here is my code:
var list = document.querySelectorAll('span[data-oe-id] img');
var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
imgsrc[i] = list[i].src;
list[i].addEventListener("mouseover",function(event)
{
console.log(imgsrc[i]); // Here it is undefined
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
list[i].addEventListener("mouseout",function(event)
{
this.src=imgsrc[i]; // Here is the same thing
});
}

Because let is brackes scope, better code will be :
var list = document.querySelectorAll('span[data-oe-id] img');
for(let i=0; i<list.length; i++){
let image = list[i];
let src = image.src;
image.addEventListener("mouseover",function(event){
console.log(src);
image.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
image.addEventListener("mouseout",function(event){
image.src=src;
});
}
Check it out and let me know.

The problem that you are having is with this. Within an event listener, this represents the event not the object calling the event.
Change this.src to list[i].src
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
to
list[i].src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
change
this.src=imgsrc[i];
to
list[i].src=imgsrc[i];

Related

Load var n from localStorage and loop n times

I'm trying to learn JS and this is my little app.
Every time I press the "INSTANTIATE" button, it instantiates a tomatoe.png in my <div>.
When the user reloads the page, the tomatoe.png should appear as many times as they've pressed the "INSTANTIATE" button.
This is the code. For this purpose, I created a variable (i), and it increments on every button press.
I planned to save this variable into localStorage, and when the page gets reloaded, I want to call a loop function that instantiates the tomatoe.png i times.
function popUp() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
i++;
localStorage.setItem("apples", i);
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
So, when the user reloads the page, as many tomatoes should appear as many times they've pressed the button.
I think I have to use a loop, but I don't know how.
Just get the item in localStorage and loop until it reaches 0, creating a new image each time (localStorage don't works in StackOverflow snippets here because of security reasons, but you get the point).
var i = 0;
function popUp() {
newImage();
i++;
localStorage.setItem("apples", i);
}
function newImage() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
}
var oldi = Number(localStorage.getItem("apples"));
while (oldi > 0) {
oldi--;
newImage();
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
First of all, you have to declare i outside your function (in case you haven't done it already) and give it a value of zero, if it isn't exist in the Local Storage:
let i = localStorage.getItem("apples") || 0;
Then, create a loop, that loops i times:
for(let n = 0; n < i; n++){}
And finally, just create tomatoes:
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
So, the full code should look like this:
document.addEventListener('DOMContentLoaded', function(){
function popUp() {
createTomato()
i++;
localStorage.setItem("apples", i);
}
function createTomato() {
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
}
document.getElementById("instantiate").addEventListener("click", popUp)
let i = localStorage.getItem("apples") || 0;
for (let n = 0; n < i; n++) createTomato();
})
<button id="instantiate">INSTANTIATE</button>
<div id="header"></div>
Try it on codepen.io

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]

How to get the img id for dynamically building IMG tags based on click like Share or Like or Comment

Good Evening Everyone.
Background: I am getting list of images from a Mongo Database and then I am calling ajax once to load those data in to particular div.
Here I am building those img tags dynamically and then appending it to a div.
Now I am trying to get the img id based on user operation, lets say clicks on 'share button' for a particular img, then I have to get the image id, and then have to look search the DB with that image id.
My code after the ajax call is:
function showImages(imageList) {
for ( var i = 0, len = imageList.length; i < len; i++) {
var elem = document.createElement("img");
elem.src = 'getImg/' + imageList[i][0] + '/' + imageList[i][1];
elem.id = imageList[i][2];
alert(elem.id);
elem.height = '100';
elem.width = '100';
elem.alt = 'SPF HYD';
/* $("a[id=shareImage]").click(function(){
var qwerty = $("img", $(this).parent()).attr("id");
alert('image id is after anchor by click...'+qwerty);
}); */
var image = document.getElementById("imageLoad");
image.appendChild(elem);
}
}
Could any one help me to get the image id onclick or any button trigger?
I threw a quick demo together to demonstrate what I meant. It's made possible using jQuery event Delagation
function showImages(imageList) {
for ( var i = 0, len = imageList.length; i < len; i++) {
var elem = document.createElement("img");
elem.src = 'getImg/' + imageList[i][0] + '/' + imageList[i][1];
elem.id = imageList[i][2];
console.log(elem.id);
elem.height = '100';
elem.width = '100';
elem.alt = 'SPF HYD';
var image = document.getElementById("imageLoad");
image.appendChild(elem);
}
}
//The event handler is registered on the document object - the second argument here is the delegate, <img>
$(document).on("click", "img", function(e) {
alert($(this).attr("id"));
});
var imageList = [[0, 1, 2], [3, 4, 5]]; //These values are merely for testing
showImages(imageList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imageLoad"></div>
Using Event Delegation is necessary here because your img tags are being dynamically generated, plus it's a lot cleaner to register one event handler for all img tags, rather than an event handler for each
Hope this helps
Use addEventListener function to add an Event Listener to your dynamically created element.
var div = document.getElementById("div");
var imgShare = document.createElement("img");
imgShare.src = "http://icons.iconarchive.com/icons/graphicloads/100-flat-2/128/share-2-icon.png";
imgShare.id = "post002";
imgShare.addEventListener("click", share);
div.appendChild(imgShare);
var imgLike = document.createElement("img");
imgLike.src = "http://www.brandsoftheworld.com/sites/default/files/styles/logo-thumbnail/public/102011/like_icon.png?itok=nkurUMlZ";
imgLike.id = "post001";
imgLike.addEventListener("click", like);
div.appendChild(imgLike);
function share(e){
alert("Share id:" + e.currentTarget.id);
}
function like(e){
alert("like id:" + e.currentTarget.id);
}
<div id="div"></div>
JSFiddle Link...

change auto image slider to link click slider

i want change this image slider, as a onclick slider.
this slider is auto slide. i need to slide each image by click a link.
DEMO check here
(function(){
document.getElementById('slideshow').getElementsByTagName('img')[0].className = "fx";
window.setInterval(kenBurns, 4000);
var images = document.getElementById('slideshow').getElementsByTagName('img'),
numberOfImages = images.length,
i = 1;
function kenBurns() {
if(i==numberOfImages){ i = 0;}
images[i].className = "fx";
if(i===0){ images[numberOfImages-2].className = "";}
if(i===1){ images[numberOfImages-1].className = "";}
if(i>1){ images[i-2].className = "";}
i++;
}
})();
Change your javascript as follows:
(function(){
document.getElementById('slideshow').getElementsByTagName('img')[0].className = "fx";
//remove the part that was auto-advancing the images on a timer
var images = document.getElementById('slideshow').getElementsByTagName('img'),
numberOfImages = images.length,
i = 1;
//set the ken burns function to go when you click "slideshow"
slideshow.onclick=function kenBurns() {
if(i==numberOfImages){ i = 0;}
images[i].className = "fx";
if(i===0){ images[numberOfImages-2].className = "";}
if(i===1){ images[numberOfImages-1].className = "";}
if(i>1){ images[i-2].className = "";}
i++;
}
})();
Edit:
http://jsfiddle.net/enigmadan/mzRxB/4/
Instead of your ken burns effect code, which removes the effect only after an image has passed, you have to remove the effect every time. This way, no matter what order you click the links, you will be able to see the effect every time.
document.getElementById('slideshow').getElementsByTagName('img')[0].className = "fx";
var images = document.getElementById('slideshow').getElementsByTagName('img');
//no longer need i
numberOfImages = images.length;
//this variable is passed in by the button clicked.
window.kenBurns = function (imageNum){
//using variable to choose image
images[imageNum].className = "fx";
//a for loop to remove 'fx' class from all images except the current one.
for(var i=0;i<numberOfImages;i++){
if(i===imageNum){ i++}
images[i].className = "";
}
};
And then call the function via links that look like this:
link1
Or if you prefer onclick:
<a onclick="kenBurns(1);" href="javascript:void(0);">link2</a>

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

Categories

Resources