JavaScript - mouseover & mouseout images - javascript

I am trying to make a simple program that allows me to mouse over one image to see another. I am really struggling with how the how to handle the first on mouseover function. I realize imageNode is undeclared, but I don't know where to declare it and what reference it is going to store.
If anyone out there could point me in the right direction to get have image1 replaced with another image in the HTML on mouseover and then return to image1 on mouseout, I would greatly appreciate it. I'm really lost right now.
I have included the HTML as well as the JavaScript below.
Thanks so much,
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
var image1 = $("image1");
var image2 = $("image2");
// preload images
var links = $("image_list").getElementsByTagName("a");
var i,
link,
image;
for ( i = 0; i < links.length; i++) {
link = links[i];
image = new Image();
image.src = link.href;
}
// attach mouseover and mouseout events for each image
image1.onmouseover = function(evt) {
link = this; //this is image that is mouseover
// set new image
//imageNode.src = link.getAttribute("href"
};
image1.onmouseout = function() {
};
image2.onmouseover = function() {
};
image2.onmouseout = function() {
};
};
<!DOCTYPE html>
<html>
<head>
<title>Image Rollover</title>
<link rel="stylesheet" type="text/css" href="rollover.css">
<script type="text/javascript" src="rollover.js"></script>
</head>
<body>
<main>
<h1>Fishing Images</h1>
<p>Move your mouse over an image to change it and back out of the
image to restore the original image.</p>
<ul id="image_list">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<p>
<img id="image1" src="images/hero.jpg" alt="">
<img id="image2" src="images/bison.jpg" alt="">
</p>
</main>
</body>
</html>
one.

If you have some html like <div id="image-rollover"></div>,
you can switch out the image on hover like this using only css:
#image-rollover {
background-color: #000;
background-image: url('SOME_IMG_URL');
background-size: cover;
height: 100px;
width: 100px;
}
#image-rollover:hover {
background-image: url('SOME_OTHER_IMG_URL');
}
Example in JSFiddle

You can do this in Javascript by a simple method:
var imgOnMouseOver = "OVER_IMG_URI";
var imgOnMouseOut = "OUT_IMG_URI";
var container = document.getElementById("IMG_TAG_ID");
container.addEventListener("mouseover", function(){
container.setAttribute("src", imgOnMouseOver);
});
container.addEventListener("mouseout", function(){
container.setAttribute("src", imgOnMouseOut);
});
Example program works fine: https://jsfiddle.net/praveen17/tv8xu67f/2/

image1.onmouseover = function() {
image1.src="images/hero.jpg"
};
image1.onmouseout = function() {
image1.src="images/release.jpg"
};
image2.onmouseover = function() {
image2.src="images/deer.jpg"
};
image2.onmouseout = function() {
image2.src="images/bison.jpg"
};
};

Related

I am trying to swap images in javascript

I am trying to swap the src image with the id image. From what I see on other examples I thought this would be the way to go about doing it. It definitely does not work for me. This is my first time posting here so any help with formatting my question would be greatly appreciated also.
HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image Rollovers</title>
<link rel="stylesheet" href="main.css">
<script src="rollover.js"></script>
</head>
<body>
<section>
<h1>Image Rollovers</h1>
<ul id="image_rollovers">
<li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li>
<li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li>
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
</ul>
</section>
</body>
</html>
Javascript:
//FUNCTION
var $ = function (id) {
return document.getElementById(id);
}
//MOUSE EVENT FUNCTIONS
var rollover = function(evt) {
var link = this;
var imageNode = $("img");
imageNode.setAttribute("img", link.getAttribute("id"));
}
var rollout = function(evt) {
var link = this;
var imageNode = $("id");
imageNode.setAttribute("id", link.getAttribute("img"));
}
//ONLOAD EVENT HANDLER
window.onload = function () {
//GET ALL IMG TAGS
var linkNode = $("image_rollovers");
var images = linkNode.getElementsByTagName("img");
//PROCESS EACH IMAGE
var i, linkNode, image;
for ( i=0; i<images.length; i++)
{
linkNode = images[i];
linkNode.onmouseover = rollover;
linkNode.onmouseout = rollout;
}
}
First, you have a typo in the HTML, you're missing the > at the end of the third <img.
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
^
Second, you're calling $("img") and $("id"), but there are no elements with those IDs. You should just be setting a variable to the appropriate attribute of link. There's no need for different functions for rollover and rollout, since they both just swap the id and src attributes.
//MOUSE EVENT FUNCTIONS
function swap_src_and_id(evt) {
var link = this;
var src = link.getAttribute("src");
link.setAttribute("src", link.getAttribute("id"));
link.setAttribute("id", src);
}
Third, you're calling linkNode.getElementsByTagName("src"), but there's no such tag. It should be img.
window.onload = function () {
//GET ALL IMG TAGS
var linkNode = $("image_rollovers");
var images = linkNode.getElementsByTagName("img");
//PROCESS EACH IMAGE
var i, linkNode, image;
for ( i=0; i<images.length; i++)
{
linkNode = images[i];
linkNode.onmouseover = swap_src_and_id;
linkNode.onmouseout = swap_src_and_id;
}
}

Programmatically setting unique onclicks to imgs in a loop in Javascript

So I have this gallery page where I have multiple <img> tags with a unique picture. Clicking on the picture should take you to a another webpage with more info on that specific picture. Hence, all onclick()s are unique, depending on the src of the image.
Now, given the fact that all these <img> tags are virtually same save for picture, I decided to use JavaScript to make all of them in a loop, as seen below:
loadImageGalleryData
for (var i = 0; i < 21; i++) {
var imgSrc = "http://localhost:63342/Performance%20Task/Website/imgs/gallery/img/" + i + ".jpg";
console.log(imgSrc);
var imgDiv = document.createElement('div');
imgDiv.className = "img";
var descDiv = document.createElement('div');
descDiv.className = "desc";
var imgView = document.createElement('img');
imgView.src = imgSrc;
imgView.onclick = (function() {{openWebpage(imgSrc);}})();
console.log(imgSrc);
imgView.width = 300;
imgView.height = 200;
imgDiv.appendChild(imgView);
imgDiv.appendChild(descDiv);
document.getElementsByTagName('body')[0].appendChild(imgDiv);
}
The openWebpage() function in particular is this one:
openWebpage()
function openWebpage(src) {
var orig = window.document.title;
window.document.title = src;
open("imagePage.html");
}
The imagePage has a jscript which tells ITS OWN img and div tag to display the image, whose source is received from window.document.opener.title or somethign like that.
All the images get built, but the onclick() doesn't register. A peek in the developer mode in Chrome, and the images don't have an onlick() attribute.
Also, if I change this snippet of code:
imgView.onclick = (function() {{openWebpage(imgSrc);}})();
into this:
imgView.onclick = function() {openWebpage(imgSrc);};
The onlick() DOES register, but for every image simultaneously, with the src of the last image created. So when I click on Picture 1, it goes to the information of Picture 22. Same goes for every other picture. It's all the same info.
What am I doing wrong here?
EDIT: ADDITIONAL INFO
imagePage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/imagePage.css"/>
<script src="jscript/imageData.js"></script>
<script src="jscript/loadImageData.js"></script>
</head>
<ul>
<li>Home</li>
<li>Gallery</li>
<li>About</li>
<li>Contact</li>
</ul>
<body>
<div>
<h1 id="imageTitle">TESTTITLE</h1>
</div>
<div>
<img id="imageView">
</div>
<div class="boxed" id="imageDesc">
</div>
</body>
</html>
loadImageData
window.onload = function() {
var imageSrc = opener.document.title;
var imageDesc = map[imageSrc];
var imageView = document.getElementById("imageView");
var imageDescView = document.getElementById("imageDesc");
imageView.src = imageSrc;
imageDescView.innerHTML = imageDesc;
};
On the last iteration of your loop, you set imgSrc to the url of picture 22. So on the click event your function openWebPage fires with that url in the argument.
Try this.
imgView.addEventListener("click", function() {openWebpage(imgSrc);});

MouseEnter / MouseOut events

I've been reading articles online, watching YouTube videos - I am lost. This is the last bit of code I have tried, which as probably changed by now as you read this. It looks so simple, I don't understand what I am doing wrong? My mind just will not grasp this. Any help? I am trying to replace the image (src) with the image in (id) when the mouse is over it. Right now I am really just trying to get an alert when I mouse over the image. Anything!
**** UPDATED CODE ****
THIS JUST IN! I'm an idiot. Javascript file wasn't directed properly, missing the sub folder. Still struggling, but now at least my rollover is working. palm to forehead
HTML:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image Rollovers</title>
<link rel="stylesheet" href="styles/main.css">
<script src="js/rollover.js"></script>
</head>
<body>
<h1>Rollover Test</h1>
<ul id="rollover_test">
<li>
<img src="images/h1.jpg" alt="img1" id="images/h4.jpg" onmouseover="MouseOver('img1');" onmouseout="MouseOut('img1')">
</li>
<li>
<img src="images/h2.jpg" alt="img2" id="images/h5.jpg">
</li>
<li>
<img src="images/h3.jpg" alt="img3" id="images/h6.jpg">
</li>
</ul>
</body>
</html>
The Javascript:
var $ = function (id) {
return document.getElementById(id);
};
function MouseOver(id){
// I'm trying to figure out the syntax in here to swap the id and src tags
alert($("id").src);
};
function MouseOut(id){
alert("out");
}
window.onload = function () {
//preload images
var links = document.getElementsByTagName("li");
var i, link, image;
for (i=0; i<links.length; i++) {
links = links[i];
image = new Image();
};
};
Actually, these simple three lines of code are enough to make it work.
$("img").on('mouseenter', function() {
$(this).attr("src", $(this).attr('id'));
});
img {
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Rollover Test</h1>
<ul id="rollover_test">
<li>
<img src="http://hd-wall-papers.com/images/wallpapers/stock-image/stock-image-15.jpg" alt="Img1" id="http://studio7designs.com/wp-content/uploads/free-stock-nature-photos.jpg">
</li>
<li>
<img src="http://studio7designs.com/wp-content/uploads/free-stock-nature-photos.jpg" alt="Img2" id="http://www.jfcsmonmouth.org/Resources/Pictures/investing-in-stocks3---ticker-symbols_s600x600.jpg">
</li>
<li>
<img src="http://www.jfcsmonmouth.org/Resources/Pictures/investing-in-stocks3---ticker-symbols_s600x600.jpg" alt="Img3" id="http://hd-wall-papers.com/images/wallpapers/stock-image/stock-image-15.jpg">
</li>
</ul>
In your HTML the id attribute has been changed to data-id just because it's best to keep the id attribute for css identification.
by using mouseenter and mouseleave in cooperation the following snippet looks at each image as encountered and swaps its src attribute into a temporary data-temp attribute attached to that image.
Hopefully the snippet comments are self explanatory.
$("li").find('img').on({
mouseenter: function() {
$this = $(this); // get the current img object
var src = $this.attr('src'), // get the current src
id = $this.attr('data-id'); //get the alternative src
$this.data('temp', src); // store in a new temporary data attribute
$this.attr('src', id);
},
mouseleave: function() {
var temp = $(this).data('temp'); // lookup temp
$(this).attr('src', temp); // swap image back
}
})
/*
var $ = function(id) {
return document.getElementById(id);
};
function MouseRollover(img) {
alert("made it");
var oldIMG = $(this).attr("src");
var newIMG = $(this).attr("id");
};
window.onload = function() {
//preload images
var links = document.getElementsByTagName("li");
var i, link, image;
for (i = 0; i < links.length; i++) {
links = links[i];
image = new Image();
}
//rollover
$("li").on('mouseenter', function() {
alert("yep");
});
}
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Rollover Test</h1>
<ul id="rollover_test">
<li>
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSm2etjS8VnJRwuZA8ormtAyPrIt8x0twLr-APiGwrkcX8NXe3P" alt="Img1" data-id="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ-W40Oxb_QCTaGT9MVgTuXaDxacAKgChfvATaS9KffbHfGc16n">
</li>
<li>
<img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTp6eZg_pJb0_NFxdaFYSnqMzPMJc-R_iwp2x8HarvdKzoNaCXv" alt="Img2" data-id="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSwvO67upMvk1q3MicNCujQ67D2EgJf8HyVA36FqM9qrv2B4Mue">
</li>
<li>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcREN8xal0JlNdcPcz-94kQqZ8t3uBWEfm3T4LWpPY5PhX7qndGp" alt="Img3" data-id="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcT07dVJl5ghqji58Su7Gs9RuSuCgleBDUITx2Dngh3ibVWzLfde">
</li>
</ul>
* SOLVED *
Once I figured out that my javascript wasn't linked right, it was just a matter of playing with syntax. Super easy. I am an idiot.
HTML
<ul id="image_rollovers">
<li>
<img src="images/h1.jpg" alt="images/h4.jpg" id="img1" onmouseenter="MouseEnter('img1');" onmouseout="MouseOut('img1')">
</li>
<li>
<img src="images/h2.jpg" alt="images/h5.jpg" id="img2" onmouseenter="MouseEnter('img2');" onmouseout="MouseOut('img2')">
</li>
<li>
<img src="images/h3.jpg" alt="images/h6.jpg" id="img3" onmouseenter="MouseEnter('img3');" onmouseout="MouseOut('img3')">
</li>
</ul>
JAVASCRIPT
var $ = function (id) {
return document.getElementById(id);
};
function MouseEnter(id){
var img = $(id);
originalURL = img.src;
var newURL = img.alt;
img.src = newURL;
};
function MouseOut(id){
var img = $(id);
img.src = originalURL;
}
window.onload = function () {
var originalURL;
//preload images
var links = document.getElementsByTagName("li");
var i, link, image;
for (i=0; i<links.length; i++) {
links = links[i];
image = new Image();
};
};
Works like a charm.
Thanks, all, for the tips and advice.

How to show a div what was hidden on img

So I have to make a hidden element (div) visible when you click on an image.
It worked on a button, but I can't seem to make it work on an image.
HTML code:
<div id="img4">
<img src="images/nummer1.png" alt="nummer1" data-hint="1"/>
</div>
<div id="hint" class="hidden">Hint 1</div>
JavaScript code:
window.onload = function () {
'use strict';
var button = document.getElementById("button");
var hint = document.getElementById("hint");
var showHint = function (event) {
console.log(this);
if data-hint === '1'
hint1.classList.toggle('hidden');
};
var img = document.querySelectorAll('img');
console.log(img);
for (var i = 0; i < img.length; i++) {
img[i].addEventListener("click", showHint);
};
function show(hint) {
};
button.addEventListener('click', show);
You see? It works on the button, but for some reason I can't make it work on an Image.
I notice you're not using jQuery. You might want to look into it, as it would make what you're trying to implement easier and much more readable.
But in any event:
hint1.classList.toggle('hidden');
Should be
hint.classList.toggle('hidden');
Also,
if data-hint === '1'
Needs to be
if (this.dataset.hint == 1)
which is how you check the data-hint attribute of this element (the one that was clicked).
http://jsfiddle.net/gunderjt/t46ws/
Should work:
$("img").click(function(){
$("div").show();
});
var showHint = function (event) {
console.log(this);
if(typeOf(hint) != 'null') hint.classList.toggle('hidden');
};
Actually you should update the hints id:s so for every image there are a corresponding hint, which shares the same id. So the first hint got a id of "hint-1".
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<style>
.hidden {
display: none;
}
.show {
display: block;
}
</style>
<div id="img4">
<img src="/test/img2.jpg" alt="nummer1" data-hint="1"/>
</div>
<div id="hint-1" class="hidden">Hint 1</div>
<script type="text/javascript">
window.onload = function() {
var images = document.getElementsByTagName("img");
for(var i=0;i<images.length;i++){
images[i].onclick = function() {
var that = this;
var id = that.getAttribute("data-hint");
var hint = document.getElementById("hint-" + id);
hint.className = "show";
};
}
};
</script>
</body>
</html>

Changing icon multiple times using onclick using javascript similar to gmail star icon

I have an icon image which changes into another image by this code
<html>
<script>
function changeImg(thisImg) {
if(prevImg) {
prevImg.src=prevSrc;
}
prevImg = thisImg;
prevSrc = thisImg.src;
thisImg.src = "flag_green.gif";
}
</script>
<body>
<img alt="" src="flag_blue.gif" id="imgClickAndChange" onclick="changeImg(this)" />
</body>
But I am unable to change it back to the previous image again after clicking the original image . please help. I want it similar like the gmail important star icon feature
Why not do it the easy way?
function changeImg(thisImg) {
if(thisImg.src == "flag_green.gif") {
thisImg.src = "flag_blue.gif";
} else {
thisImg.src = "flag_green.gif";
}
}
This might work:
var c = 0;
var images = ['src-for-first-image.jpg','src-for-second-image.jpg'];
$('.trigger').on('click', function() {
$('.image').attr('src', images[c % images.length]);
c++;
});
this lets you loop through many images.
Example:
jsfiddle
Try this: http://jsfiddle.net/pUbrv/
<script>
var altImg = "http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg";
var tmpImg = null;
function changeImg(thisImg) {
tmpImg = thisImg.src;
thisImg.src = altImg;
altImg = tmpImg;
}
</script>
<body>
<img alt="" src="http://www.gettyicons.com/free-icons/136/stars/png/256/star_gold_256.png" id="imgClickAndChange" onclick="changeImg(this)" />
</body>
----------------- EDITED ----------------------
It's probably easier to load both images and toggle the visibility, rather than changing the src of a single img tag.
Try something like this http://jsfiddle.net/qXYGp/:
<span onclick="toggleImg(this)">
<img src="http://ww1.prweb.com/prfiles/2011/10/12/8875514/star_white.jpg" />
<img src="http://www.gettyicons.com/free-icons/136/stars/png/256/star_gold_256.png" style="display: none"/>
</span>
and for JS:
toggleImg = function(container) {
var imgs = container.getElementsByTagName('img');
for (i in imgs) {
if (imgs[i].style.display == 'none')
imgs[i].style.display = 'inline';
else
imgs[i].style.display = 'none';
}
}

Categories