Hi guys I have a simple rollover onmouseover effect, I have tried several scripts but none of them work, can anyone tell me why?`
javascript:
<script language="JavaScript" type="text/javascript">
<!--
if (document.images) {
homebuttonup = new Image();
homebuttonup.src = "./images/gym-light.png";
homebuttondown = new Image();
homebuttondown.src = "./images/buttonright.png";
}
function buttondown(buttonname) {
if (document.images) {
document[buttonname].src = eval(buttonname + "down.src");
}
}
function buttonup(buttonname) {
if (document.images) {
document[buttonname].src = eval(buttonname + "up.src");
}
}
// -->
</script>
and link:
<a href="index.html" onmouseover="buttondown('homebutton')" onmouseout="buttonup('homebutton')">
<img id='Img4Inner' name="homebutton" src='./images/gym-light.png' alt="" />
</a>
**UPDATE 2 (last one lol) **
you currently have the onmouseout and onmouseover on the a tag, move them to the image tag and it will work:
you're code:
<a onmouseout="buttonup('homebutton')" onmouseover="buttondown('homebutton')"
href="http://www.[...].com" style="height:120px;width:100px;">
<img id="Img4Inner" alt="" src="http://[..].com/images/gym-light.png" name="homebutton">
</a>
Working code:
<a onmouseout="buttonup('homebutton')" onmouseover="buttondown('homebutton')"
href="http://www.[...].com" style="height:120px;width:100px;">
<img alt="" src="http://[...]/images/gym-light.png" onmouseout="buttonup(this)"
onmouseover="buttondown(this)" name="homebutton" id="Img4Inner">
</a>
Update: because you're invoking the functions on the anchor tags they need to have a height and a width similar to the following (place your height and width accordingly):
<a style="height:25px;width:25px;" href="http://www.[...].com"
onmouseover="buttondown('homebutton')" onmouseout="buttonup('homebutton')">
...
</a>
and I"m out...
I just used firebug, edited the HTML with the height and width and it worked fine :
)
and while I"m sure that will solve the problem.. the doctype is set to <!doctype html> and should be something like what's here (LINK)
if you would've implemented the below approach, the image would have a height and width, and since that is the image that is being targeting, might make more sense..
http://jsfiddle.net/ETHaM/2/
if (document.images) {
homebuttonup = new Image();
homebuttonup.src = "http://www.placekitten.com/100/100/";
homebuttondown = new Image();
homebuttondown.src = "http://dummyimage.com/100x100/000/fff";
}
function buttondown(obj) {
if (document.images) {
obj.src = eval(obj.name+ "down.src");
}
}
function buttonup(obj) {
if (document.images) {
obj.src = eval(obj.name + "up.src");
}
}
<a href="index.html">
<img id='Img4Inner' onmouseover="buttondown(this)" onmouseout="buttonup(this)" name="homebutton" src='http://www.placekitten.com/100/100/' alt="" />
</a>
Your code works
Here is however a more unobtrusive version
http://jsfiddle.net/mplungjan/927nN/
<a href="index.html" id="homeLink"><img
id='Img4Inner' class="hoverImg"
name="homebutton" src='http://www.placekitten.com/100/100/' alt="" /></a>
<a href="about.html" id="aboutLink"><img
id='Img5Inner' class="hoverImg"
name="aboutbutton" src='http://www.placekitten.com/100/100/' alt="" /></a>
var buttons={};
if (document.images) {
buttons["homebuttonup"] = new Image();
buttons["homebuttonup"].src = "http://www.placekitten.com/100/100/";
buttons["homebuttondown"] = new Image();
buttons["homebuttondown"].src = "http://dummyimage.com/100x100/000/fff";
buttons["aboutbuttonup"] = new Image();
buttons["aboutbuttonup"].src = "http://www.placekitten.com/100/100/";
buttons["aboutbuttondown"] = new Image();
buttons["aboutbuttondown"].src = "http://dummyimage.com/100x100/000/fff";
}
window.onload=function() {
var images = document.getElementsByTagName("img");
for (var i=0,n=images.length;i<n;i++) {
if (images[i].className=="hoverImg") {
images[i].parentNode.onmouseover=function() {
var buttonname=this.id.replace("Link","button");
document[buttonname].src = buttons[buttonname + "down"].src;
}
images[i].parentNode.onmouseout=function() {
var buttonname=this.id.replace("Link","button");
document[buttonname].src = buttons[buttonname + "up"].src;
}
}
}
}
Related
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.
I'm relatively new into html, css and javascript. So far, I have a landing page with a thumbnail gallery. For different reasons, every thumbnail is located in a different div. I used javascript to make the thumbnail change when I click inside the div, and the thumbnail changes. The problem is: when I change to another div I need to click two times to make the script start working.
My html and js code is:
<div id="thumb1" class="fluid"><img src="img/image2.jpg" img id="img1" alt=""/></div>
<script type="text/javascript">
var images = ["img/image1.jpg",
"img/image2.jpg",
"img/image3.jpg"
],
i = 1;
for (var j=images.length; j--;) {
var img = new Image();
img.src = images[j];
}
document.getElementById('img1').addEventListener('click', function() {
this.src = images[i >= images.length - 1 ? i = 0 : ++i];
}, false);
</script>
<div id="thumb2" class="fluid"><img src="img/imageC.jpg" img id="img2" alt=""/></div>
<script type="text/javascript">
var images2 = [
"img/imageA.jpg",
"img/imageB.jpg",
"img/imageC.jpg",
"img/imageD.jpg"
],
i = 1;
for (var j=images2.length; j--;) {
var img2 = new Image();
img2.src = images2[j];
}
document.getElementById('img2').addEventListener('click', function() {
this.src = images2[i >= images2.length - 1 ? i = 0 : ++i];
}, false);
</script>
Is there a way to convert this two scripts (or more) into only one in a simple an easy way? Right now, the script is the same but I don't feel like duplicating the script each time for every div is the most reasonable way to proceed. Moreover, since I will need more than two div, like nine or ten... I don't want a bunch of useless code...Any help would be appreciated. Thank you very much.
You could use this solution, where you put all your images inside every div, but every time, all the images are hidden except one, and the onClick listener changes the display property.
<html>
<body>
<script type="text/javascript">
function getOnlyImagesFromArray(nodeList) {
var onlyImagesArray = [];
var nodeListAsArray = Array.prototype.slice.call(nodeList, 0);
nodeListAsArray.forEach( function(element) {
if(element.localName == 'img') {
onlyImagesArray.push(element);
}
});
return onlyImagesArray;
}
function handleClick() {
// using JQuery here would be much cleaner, but out of shear lazyness, I've created the helper function "getOnlyImagesFromArray"
var onlyImages = getOnlyImagesFromArray(this.childNodes);
var visibleIndex = -1;
for(var i = 0; i < onlyImages.length; i++) {
if(onlyImages[i].style.display == 'inline') {
visibleIndex = i;
break;
}
};
onlyImages[visibleIndex].style.display = "none";
onlyImages[visibleIndex >= onlyImages.length - 1 ? visibleIndex = 0 : ++visibleIndex].style.display = "inline";
}
</script>
<div id="thumb1" class="fluid">
<img src="img/image1.jpg" img id="img1" alt="" style="display:none"/>
<img src="img/image2.jpg" img id="img1" alt="" style="display:inline"/>
<img src="img/image3.jpg" img id="img1" alt="" style="display:none"/>
</div>
<script type="text/javascript">
document.getElementById('thumb1').addEventListener('click', handleClick, false);
</script>
<div id="thumb2" class="fluid">
<img src="img/imageA.jpg" img id="img2" alt="" style="display:none"/>
<img src="img/imageB.jpg" img id="img2" alt="" style="display:none"/>
<img src="img/imageC.jpg" img id="img2" alt="" style="display:inline"/>
<img src="img/imageD.jpg" img id="img2" alt="" style="display:none"/>
</div>
<script type="text/javascript">
document.getElementById('thumb2').addEventListener('click', handleClick, false);
</script>
</body>
</html>
Your problem is that when you use var inside an inline script, it always create it in main scope (i.e. window).
e.g.:
<script type="text/javascript">
var i = 1;
//...your code
</script>
<script type="text/javascript">
var i = 2;
//...your code
</script>
Both scripts assign value into window.i which will be equal to 2 in both scripts.
To make it separate, wrap each script into a function like this:
<script type="text/javascript">
(function() {
var i = 1;
//...your code
})();
</script>
<script type="text/javascript">
(function() {
var i = 2;
//...your code
})();
</script>
Or simple instead of i use something more specific, e.g. imageIndex1 and imageIndex2.
More experienced developers may write it like this, which is a bit shorter but less readable for beginners:
<script type="text/javascript">
(function(i) {
//...your code
})(1);
</script>
<script type="text/javascript">
(function(i) {
//...your code
})(2);
</script>
I have the following markup:
<h1 id="logoImage">
<a href="/">
<img src="http://path-to-image.jpg" alt="Title of site" />
</a>
</h1>
I would like to get the values of "src" and "alt", and use them in a little different way, along with removing the image element from the page.
<h1 id="logoImage">
<a href="/" style="background-image: url('http://path-to-image.jpg')">
Title of Site
</a>
</h1>
I'm not too familiar with plain ol' JavaScript, so, this has me quite stumped.
Any thoughts on how to solve this?
window.addEventListener('load', function load(){
var logo = document.getElementById('logoImage'),
img,
parent;
if (!logo) {
return;
}
img = logo.querySelector('img');
if (!img) {
return;
}
parent = img.parentNode;
parent.style.backgroundImage = 'url(' + img.src + ')';
parent.style.display = 'block';
parent.style.width = img.width + 'px';
parent.style.height = img.height + 'px';
parent.textContent = img.alt;
});
http://jsfiddle.net/q7brkkbt/1
I am trying to add a link to a single image that already has a change source function attached to it.
The site has a gallery that uses thumbnails to change the larger image so there are 27 images. I am triyng to add an individual link to one of this images.
all the code i am finding uses id's and in order to keep the change source function working, none of these solutions will work.
The link is for only one image. Here is my code:
<script>function changeImage27()
{
var img = document.getElementById("image");
img.src="thestudio/thestudio_27.gif";
}
</script>
And my HTML:
<div id="slideshow">
<img id="image" src="thestudio/thestudio_1.gif" />
</div>
<a id="clickme" onClick="changeImage();"><img border="0"src="thestudio/thestudio_1t.gif"></a>
I only need to link one image. so i am looking for a solution that adds a hyperlink in the script. a.href="" is not working and i cant seem to find any other solutions.
This may be a better solution:
<head>
<script type="text/javascript">
var images = ["image1.gif","image2.gif",...,"image27.gif"];
var thumbs = ["image1t.gif","image2t.gif",...,"image27t.gif"];
var basePath = "thestudio/";
var currentImage = 0;
function changeImage() {
var img = document.getElementById("image");
var thumb = document.getElementById("thumb");
img.src = basePath + images[currentImage];
thumb.src = basePath + thumbs[currentImage];
currentImage ++;
if (currentImage >= images.length) {
currentImage = 0; // this will cause it to loop
}
}
</script>
</head>
<body onLoad="changeImage();">
<div id="slideshow">
<img id="image">
</div>
<a onClick="changeImage();" href="#"><img border="0" id="thumb"></a>
</body>
So you don't have to have 27 different functions.
You could also define the images like follows:
var images = [{image:"image1.gif",thumb:"image1t.gif"},...{image:"image27.gif",thumb:"image271.gif"}];
Then in changeImage:
var image = images[currentImage];
img.src = basePath + image.image;
thumb.src = basePath + image.thumb;
Here you go:
Take a look at this JSFiddle I put together for you.
Cheers!
http://jsfiddle.net/douglasloyo/aR83b/
<script>
window.changeImage = function changeImage()
{
var img = document.getElementById("my-img");
var newImgSrc = "http://www.johnlund.com/ArticleImages/Artcl38-stock-ideas/dog-leader-pack.jpg";
img.src=newImgSrc;
}
</script>
<img id="my-img" src="http://www.johnlund.com/ArticleImages/Artcl38-stock-ideas/ocean-island- palm.jpg" />
<button onclick="window.changeImage();">ClickMe</button>
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';
}
}