Saving the original image before mouseover - javascript

I am trying to realize JavaScript that would change image on mouseover and revert it back, when mouseout. I have this code for that:
var list = document.querySelectorAll('span[data-oe-id] img');
var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
imgsrc[i] = list[i].src;
console.log(imgsrc[i]);
list[i].addEventListener("mouseover",function(event){event.target.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";},false);
list[i].addEventListener("mouseout",function(event){event.target.src=imgsrc[i];},false);
}
It is changing image on mouseover perfectly fine, but on mouseout, image is changed to undefined. For example:
<img src="undefined" class="img img-fluid" alt="A4Tech Bloody V8M">
Is result after mouseout

Src attribute cannot be set using event argument. you can use this keywords to access same selected element.
View Output in full screen
var list = document.querySelectorAll('img');
var i;
var imgsrc=[];
for(i=0;i<3;i++)
{
imgsrc[i] = list[i].src;
list[i].addEventListener("mouseover",function()
{
this.src="https://media1.giphy.com/media/PfFtibPKBbQrK/giphy.gif?cid=ecf05e47b668e5062e9a561e681f23705e106d8d495b3915&rid=giphy.gif";
});
list[i].addEventListener("mouseout",function()
{
this.src=imgsrc[i];
});
}
<img id="1" src="1" alt="img1"/>
<img id="2" src="2" alt="img2"/>
<img id="3" src="3" alt="img3"/>

Related

Could not bind event to each item in array loop

I want to add an event to every image in the document, this is the code:
let images = document.getElementsByTagName("img")
const self = this;
for (var img of images) {
img.onclick = function(e) {
e.stopPropagation();
if (!e.target.src) {
return;
}
self.source = e.target.src;
self.alt = e.target.alt;
}
}
I log all of the images and find that only the last image has the click event. I had tried converting images into an array and used forEach methods, which got the same result. What's up?
By the way, I do that in Vue's mounted hook method.
Best way to attach events to multiple DOM elements is to use Event Delegation. You should attach the event to the parent element and check if the target element is img or not. Then you can access the src and alt attributes of the image.
var images = document.querySelector('.images');
images.onclick = function(e) {
if(e.target.tagName === 'IMG') {
console.log(e.target.src +" : " + e.target.alt);
}
}
<div class="images">
<img alt="1" src="https://randomuser.me/api/portraits/men/83.jpg" />
<img alt="2" src="https://randomuser.me/api/portraits/med/men/83.jpg" />
<img alt="3" src="https://randomuser.me/api/portraits/thumb/men/83.jpg" />
</div>

Implementing mouseover/mouseout for many images in an external JavaScript file

I'm trying to enable onMouseOver and onMouseOut for all of my icons and replacing them with unique icons.
Originally I had this:
<img id="EEProfile" src="images/EEProfile.png" alt="Employee Profile" onMouseOver="mouseOver()" onMouseOut="mouseOut()">
External JS file:
function mouseOver() { document.getElementById("EEProfile").src = 'images/EEProfile_Hover.png'; }
function mouseOut() { document.getElementById("EEProfile").src = 'images/EEProfile.png'; }
There are a few issues with this:
This method works on IE but for some reason on Chrome onMouseOut isn't working, so hover images are remaining.
Requires some inline javascript. I'm trying to move towards eliminating all inline JS.
Requires me to hardcode image paths for each and every image on the page.
Since all image paths are the same and follow the same naming convention, which is just
'images/ImageID.png' or 'images/ImageID_Hover.png'
I was hoping to implement something like this:
Pseudocode HTML:
<img id="EEProfile" src="images/EEProfile.png" alt="Employee Profile" onMouseOver="mouseOver(this.id)" OnMouseOut="mouseOut(this.id)">
Pseudocode JavaScript:
function mouseOver(id) { document.getElementById("id").src = 'images/id.png'; }
function mouseOut(id) { document.getElementById("id").src = 'images/id_Hover.png'; }
I want to pass over the ID of the image element to the mouseOver and mouseOut functions as a parameter, then use that ID's string literal in the image path so I don't have to hardcode every image's path. Is something like this possible? Is there a way to do this without inline JS?
I've considered using content:hover without JS but it isn't supported in IE.
I would give all the images you want to have the hover effect a specific class name. Then you can get all the element with that class and add event listeners for mouseover and mouseout. I used the current src to determine the new src. You could just as easily get the id with event.target.id and use that to build the src. You also could build the regular expression to match more than just .png files.
(function(window, document, undefined)
{
var images = document.getElementsByClassName('hoverImage');
for (var i = 0; i < images.length; i++) {
images[i].addEventListener('mouseover', imageMouseOver, false);
images[i].addEventListener('mouseout', imageMouseOut, false);
}
})(window, window.document);
function imageMouseOver(event)
{
event = event || window.event;
var image = event.target;
image.src = getNewImagePath(image.src);
console.log(image);
}
function imageMouseOut(event)
{
event = event || window.event;
var image = event.target;
image.src = getNewImagePath(image.src);
console.log(image);
}
function getNewImagePath(path)
{
var newPath;
if (path.indexOf('_Hover') === -1) {
newPath = path.replace('.png', '_Hover.png');
} else {
newPath = path.replace('_Hover', '');
}
return newPath;
}
.hoverImage {
width: 50px;
height: 50px;
}
<img id="1" src="images/1.png" alt="Employee Profile" class="hoverImage">
<img id="2" src="images/2.png" alt="Employee Profile" class="hoverImage">
<img id="3" src="images/3.png" alt="Employee Profile" class="hoverImage">

Javascript, A sytax returns two different values?

Display the image the mouse hovers on, clearing the <ul>
But when I store the src attribute of the <img> in a
variable it returns two different src. Like src of the
image , at the point and the modified one by the substring
Eg:
//images/Hassum_Harrod_03.jpg
//images/Hassum_Harrod.jpg
I want only a single output not two why does this happen please give a reason.
Note
If <img src="images/Hassum_Harrod_03_tn.jpg" /> THUMBNAIL
If <img src="images/Hassum_Harrod_03" /> FULL IMAGE
HTML CODE
<body>
<div id="art">
<h2>Art Preview</h2>
<p>Mouse over the following pieces of art to preview a large version</p>
<ul class="grid">
<li><img src="images/Hassum_Harrod_03_tn.jpg" alt="Hassum Harod's Summer Trees"></li>
<li><img src="images/LaVonne_LaRue_02_tn.jpg" alt="LaVonne_LaRue's Mighty Duck"></li>
<li><img src="images/Lorenzo_Garcia_01_tn.jpg" alt="Lorenzo Garcia's The Dancer"></li>
<--FEW OTHER <li>'s-->
</div>
<script src="script.js"></script>
</body>
Javascript
document.querySelector('.grid').addEventListener('mouseover', function(e) {
if (e.target.tagName === 'IMG') {
ulNode = e.target.parentNode.parentNode;
var getAtt = e.target.getAttribute('src');
var imgLoc = getAtt.substring(0,getAtt.length-7)+".jpg";
console.log(imgLoc); //images/Hassum_Harrod_03.jpg
//images/Hassum_Harrod.jpg
var createElement = document.createElement("img");
createElement.setAttribute("src",imgLoc);
ulNode.innerHTML="";
ulNode.appendChild(createElement);
} // check to see that I clicked on IMG only
}, false); // click event
The first time you mouseover the "Hassum_Harrod_03_tn.jpg", the code:
getAtt.substring(0,getAtt.length-7)+".jpg"
should return the "images/Hassum_Harrod_03.jpg". However when it runs to:
var createElement = document.createElement("img");
createElement.setAttribute("src",getAtt + ".jpg");
ulNode.innerHTML="";
ulNode.appendChild(createElement);
The DOM was broken now as the "ul" element contains no "li" at all but an "img" in it.
Note the "mouseover" binding still works as the "ul" still lives.
Then a second mouseover on the "Hassum_Harrod_03.jpg" will get "Hassum_Harrod.jpg" and the "ulNode" in your code is no longer the "ul" but the upper "div" node. And the "mouseover" binding fails as no "ul" exists.
I guess this would work!
document.querySelector('.grid').addEventListener('mouseover', function(e) {
if (e.target.tagName === 'IMG') {
ulNode = e.target.parentNode.parentNode;
var getAtt = e.target.getAttribute('src');
var imgLoc = getAtt.substring(0,getAtt.length-7)+".jpg";
console.log(imgLoc); //images/Hassum_Harrod_03.jpg
//images/Hassum_Harrod.jpg
var createElement = document.createElement("img");
createElement.setAttribute("src",getAtt + ".jpg");
ulNode.innerHTML="";
ulNode.appendChild(createElement);
} // check to see that I clicked on IMG only
}, false); // click event
<div id="art">
<h2>Art Preview</h2>
<p>Mouse over the following pieces of art to preview a large version</p>
<ul class="grid">
<li><img src="images/Hassum_Harrod_03_tn.jpg" alt="Hassum Harod's Summer Trees" /></li>
<li><img src="images/LaVonne_LaRue_02_tn.jpg" alt="LaVonne_LaRue's Mighty Duck" /></li>
<li><img src="images/Lorenzo_Garcia_01_tn.jpg" alt="Lorenzo Garcia's The Dancer" /></li>
</ul>
</div>
The reason is, the onMouseOver event binds the image by changing it to the full version. That's the reason you get so.
You are facing this issue because your are binding mouseover event for all img element (the one you created dynamically also) just check classname of in mouseover function will work, I guess.
document.querySelector('.grid').addEventListener('mouseover', function(e) {
if (e.target.tagName === 'IMG') {
ulNode = e.target.parentNode.parentNode;
if(ulNode.className == 'grid'){
var getAtt = e.target.getAttribute('src');
var imgLoc = getAtt.substring(0,getAtt.length-7)+".jpg";
alert(imgLoc); //images/Hassum_Harrod_03.jpg
//images/Hassum_Harrod.jpg
var createElement = document.createElement("img");
createElement.setAttribute("src",imgLoc);
ulNode.innerHTML="";
ulNode.appendChild(createElement);
}
} // check to see that I clicked on IMG only
}, false); // click event
document.querySelector('.grid').addEventListener('mouseover', function(e) {
if (e.target.tagName === 'IMG') {
ulNode = e.target.parentNode.parentNode;
ulNode.innerHTML="";
var getAtt = e.target.getAttribute('src');
var imgLoc = getAtt.substring(0,getAtt.length-7)+".jpg";
console.log(imgLoc); //images/Hassum_Harrod_03.jpg
//images/Hassum_Harrod.jpg
var createElement = document.createElement("img");
createElement.setAttribute("src",imgLoc);
ulNode.appendChild(createElement);
} // check to see that I clicked on IMG only
}, false); // click event

How do I exchange two images in a webpage (on two consecutive clicks) using jQuery?

I have two images among many that I want to swap places between. If I click on one image, then the other, the respective images should swap with each other and the rest should remain the same. I'm a beginner at this so any help or direction would be helpful.
This works also for every image:
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
<img src="http://stunningwebsitetemplates.files.wordpress.com/2011/12/jquery.png"/>
<img src="http://bloggerschmidt.de/images/stories/logo-mootools.gif" />
JS
$(function(){
var src="";
var old;
$("img").click(function(){
if(src=="")
{
src=$(this).attr("src");
old=$(this);
}
else
{
old.attr("src",$(this).attr("src"));
$(this).attr("src",src);
src="";
}
});
});​
Another solution without any global variable.
html
<div id="images">
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
$('img').click(function(){
if($('#images img').hasClass('selected')){
var src = $(this).attr('src');
$('.selected').attr('src',src);
$(this).attr('src',$('.selected').attr('src'));
$(this).removeClass('selected');
}
else
$(this).addClass('selected');
});
Here is a different approach that swaps the actual elements rather than the src of the img, also avoids using external variables for the swap.
$('img.swap').on('click', function() {
var t = $(this);
if (t.hasClass('clicked')) {
t.removeClass('clicked');
return;
}
var clicked = $('img.swap.clicked')
if (clicked.length === 0) {
t.addClass('clicked');
return;
}
var placeHolder = $('<div id="placeholder"></div>');
clicked.before(placeHolder);
t.after(clicked);
placeHolder.before(t).remove();
clicked.removeClass('clicked');
});​
Example - http://jsfiddle.net/BxST9/3/ (using div instead of img but shouldn't make a difference)
See the example on: http://jsfiddle.net/Lvp4j/1/
var selected;
$("img").click(
function() {
if (!selected)
{
selected = this;
$(selected).addClass("selected");
}
else
{
var src1 = $(selected).attr("src");
var src2 = $(this).attr("src");
$(this).attr("src", src1);
$(selected).attr("src", src2);
$(selected).removeClass("selected");
selected = null;
}
}
);
My code adds also a selected class so you can highlight the clicked image...
try below code
html
<div>
<img scr="/images/1.jpg" />
<img scr="/images/2.jpg" />
<img scr="/images/3.jpg" />
<img scr="/images/4.jpg" />
<img scr="/images/5.jpg" />
</div>
Js file
(function() {
var swapArray = [];
var count=0;
$('img').click(function(){
count++;
swapArray.push($(this).attr('src'));
$(this).addClass(count);
if(count==2){
$('.1').attr('src',swapArray[1]).removeClass('1');
$('.2').attr('src',swapArray[0]).removeClass('2');
swapArray.length = 0;
count=0;
}
});
}());​
Given this HTML:
<img src="image_1.jpg" />
<img src="image_2.jpg" />
<img src="image_3.jpg" />
<img src="image_4.jpg" />
You could use the following JavaScript:
(function() {
var previous = null;
$('img').click(function() {
var current = $(this);
if (current.is(previous)) { // clicked same image twice; reset
reset_clicked();
} else if (previous != null) { // two images clicked; swap
swap_src(previous, current);
reset_clicked();
} else {
set_clicked(current);
}
});
function reset_clicked() {
previous.removeClass('clicked');
previous = null;
}
function set_clicked(img) {
img.addClass('clicked');
previous = img;
}
function swap_src(img1, img2) {
var src1 = img1.attr('src');
img1.attr('src', img2.attr('src'));
img2.attr('src', src1);
}
}());​
The 'clicked' class is added purely so you can use CSS to style clicked images. This class could also be used to identify any previously-clicked images, but I've used a JavaScript variable instead because that's quicker than a DOM lookup.
There's a demo on JSFiddle: jsfiddle.net/cvthL/2
This answer was posted as an improved version of Jitendra Pancholi's first answer and an alternative to his/her second answer.

Swap multiple images from javascript array

I am coding a website with multiple pages of thumbnail image galleries. I want to populate the thumbnail images on each page from an array, so that I won't have to change the path of multiple images on each page. The folder path is defined in a var statement - which I would like to be the only unique element on each gallery page - and the images in each gallery's folder will have the same names (t1.jpg, t2.jpg, etc.).
I have the main image swap working, and tried to use a similar function for the thumbnails, but it doesn't work because the image ID is the same for all the thumbnail images. I could give each image a unique ID, but then would have to call a separate function for each thumbnail swap (15 per page).
I am a javascript novice and despite much searching I can't figure out how to work around this or find any similar examples. Any help or advice would be appreciated.
Javascript:
<script language="JavaScript" type="text/javascript">
<!--
// Thumbnail Image Array
var imgThumbs = new Array (
"t1.jpg",
"t2.jpg",
"t3.jpg"
)
//Main Image Array
var imgArray = new Array (
"f1.jpg",
"f2.jpg",
"f3.jpg"
)
//Image Path
var imgPath = "images/portfolio/samples/";
function preloadImages() {
for(var i = 0; i < imgArray.length; i++) {
var tmpImg = new Image;
tmpImg.src = imgPath + imgArray[i];
}
}
//Thumbnail Image Swap Function
function loadThumb(thumbID) {
var theThumb = document.getElementById('theThumb');
var newThumb;
newThumb = imgThumbs[thumbID];
theThumb.src = imgPath + newThumb;
}
//Main Image Swap Function
function swapImage(imgID) {
var theImage = document.getElementById('theImage');
var newImg;
newImg = imgArray[imgID];
theImage.src = imgPath + newImg;
}
//-->
</script>
HTML:
<div id="portfolio">
<div id="thumbnails">
<img src="images/portfolio/noThumb.jpg" id="theThumb" onload="loadThumb(0)" alt="Architect Portfolio Thumbnail 1" width="75" height="75" />
<img src="images/portfolio/noThumb.jpg" id="theThumb" onload="loadThumb(1)" alt="Architect Portfolio Thumbnail 2" width="75" height="75" />
<img src="images/portfolio/noThumb.jpg" id="theThumb" onload="loadThumb(2)" alt="Architect Portfolio Thumbnail 3" width="75" height="75" />
</div>
<div id="mainImage"><img src="images/portfolio/samples/f1.jpg" alt="Architecture Portfolio Main Image" id="theImage" /></div>
</div>
Each ID attribute on the page should be unique. Remove them and rewrite your code as:
function loadThumb(thumbID, obj) {
var newThumb = imgThumbs[thumbID];
obj.src = imgPath + newThumb;
}
And the corresponding HTML part will look like
<img src="images/portfolio/noThumb.jpg" onload="loadThumb(0, this)"
alt="Architect Portfolio Thumbnail" width="75" height="75" />
ps: Actually I do not see the purpose of that script - onload function could be triggered before the image is loaded in a preloadImages() function.
pps: try this code http://jsfiddle.net/4cKvs/ and jQuery variant http://jsfiddle.net/zSBNR/
If you are a Javascript novice I recommend you to search in google about
jQuery it is can help you a lot (Google also using it).

Categories

Resources