Javascript Image Links - javascript

I have 5 image links that will display another image within that same id when clicked to an active page. So far I got the all images to change to one image, but I want them to revert back to the original image when another image link is clicked. I understand I can do this using HTML and CSS, but I'd like to know how to use JavaScript for this feature.
Here is the HTML:
<img src="images/tn_wolverine.jpg" id="imgBox1">
<img src="images/tn_wolverine.jpg" id="imgBox2">
Here is the JavaScript:
function changeImg(ID) {
var obj = document.getElementById("imgBox"+ID).src="images/tn_wolverine2.jpg";
}

You need to use a flag to record the index of the lastest clicked image. Use this index to revert the image back to the original picture when user click another image. And then replace the prev index flag with the new one.
I wrote a simple "poker" example: Live DEMO
HTML
<a href="#">
<img class="poker" src="http://pic1a.nipic.com/2009-03-03/200933143727699_2.jpg"/>
</a>
<a href="#">
<img class="poker" src="http://pic1a.nipic.com/2009-03-03/200933143727699_2.jpg"/>
</a>
JavaScript
(function(){
var pokers = document.getElementsByClassName("poker"),len=pokers.length,imgs=["http://pica.nipic.com/2007-10-16/20071016115825247_2.jpg","http://img.teapic.com/thumbs/201210/23/141801plfndrdzabzjdaok.jpg.middle.jpg"];
var defaultImg = "http://pic1a.nipic.com/2009-03-03/200933143727699_2.jpg";
var prevIndex = -1;
for(var i=0;i<len;i++){
pokers[i].addEventListener("click",(function(index){
return function(){
//no action if user clicked the same poker
if(prevIndex===index) return;
if(prevIndex!==-1)pokers[prevIndex].src=defaultImg;
prevIndex = index;
this.src=imgs[index];
};
})(i));
};
})();

Related

Use Javascript to make image go back to original - OpenCart 2.3

I wrote some JS that lets me replace the main image on a product page with that a different image. This part is working great. However, I need the original image to return once the mouse leaves. I cannot get this to work.
Also, I would like to add a delay to this so that when I remove the mouse there is like a 1/4 second delay before changing back to the original image. This is all being done on the product page of OC 2.3.
this.imagePreview = function(){
$("a.preview").mouseleave(function(e){
$("#image").attr("src",default_image);
});
$("a.preview").hover(function(e){
$("#image").attr("src",this.rel);
});
$(document).ready(function(){
default_image = $("#image").attr("src");
imagePreview();
});
Can someone help me write this little bit of extra code? Everything else I've tried doesnt work.
You can get the desired result using JavaScript.
(function() {
var img, defaultImage, preview, i, hnd;
img = document.getElementById("image"); // Gets the image element.
defaultImage = img.src; // Sets the image src attribute to the defaultImage variable.
preview = document.querySelectorAll(".preview"); // Gets the elements with css selector is «.preview».
for (i = 0; i < preview.length; i++) {
/* Adds the mouseover event to the preview element. */
preview[i].addEventListener("mouseover", function() {
img.src = this.rel;
clearTimeout(hnd); // Reset the timeout handler.
});
/* Adds the mouseleave event to the preview element. */
preview[i].addEventListener("mouseleave", function() {
hnd = setTimeout(function() {
img.src = defaultImage;
}, 250); // 1/4 second delay.
});
}
})();
#list li {
margin: 10px;
}
<img id="image" src="https://cdn1.iconfinder.com/data/icons/technology-and-hardware-2/200/vector_66_08-32.png" />
<ul id="list">
<li>
<a class="preview" href="#" rel="https://cdn3.iconfinder.com/data/icons/device-icons-2/512/BT_computer-32.png">Computer</a>
</li>
<li>
<a class="preview" href="#" rel="https://cdn4.iconfinder.com/data/icons/48-bubbles/48/29.Mac-32.png">Mac</a>
</li>
<li>
<a class="preview" href="#" rel="https://cdn2.iconfinder.com/data/icons/crystalproject/32x32/devices/laptop.png">Laptop</a>
</li>
</ul>
Try this code:
$("a.preview").mouseleave(function(){
setTimeout(function () {
var default_image = $("#defaultImage").attr("src");
$("#image").attr("src",default_image);
}, 3000);
});

Change a "href" and img "src" value on refresh using javascript

I want to change the image and anchor link on refresh for my banners. I have 4 different banner images and 4 different links for each banner. So I need when user refresh the page each banner will load with own URL.
HTML code :
<div class="ad_body">
<a href="http://www.domain.com/" target="_blank">
<img src="images/banner/partner1.jpg">
</a>
</div>
Thanks for any help.
You could add images sources you have in array then choose from this array randomly :
$(function(){
var links = ["link1", "link2", "link3"];
var arr = ["partner1.jpg", "partner2.jpg", "partner3.jpg"];
var random = Math.floor(Math.random() * arr.length) + 0;
$(".ad_body a").attr("href", links[random]);
$(".ad_body img").attr("src", "images/banner/"+arr[random]);
});
Hope this helps.

Change image within div on image icon click

I have created a Javascript function which will allow me to change the image to another when the div is directly clicked but I am trying to get this function to work depending on which other image icon i select.
As you can see by the above image, i have a main div which contains a picture on browser load, and two further thumbnail divs which include different pictures, I want to create the function to change the main div if one of the smaller thumbnail divs are selected.
Current Javascript Function
function diffImage(img) {
if(img.src.match(/blank/)) img.src = "bognor.jpg";
else img.src = "images/bognor2.jpg";
}
Thanks in advance,
Sam
You would just use onclick event listeners on the icons and the function would change the large image to the image of the item clicked:
document.getElementById("icon1").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
document.getElementById("icon2").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
If you happen to have several icons you could make an icon class and apply the event listener like so:
var icons = document.getElementsByClassName("icon");
for(var i=0; i<icons.length; i++) {
icons[i].onclick = function(){
document.getElementById("main").src = this.src;
}
}
Fiddle Example for using classes
Although it's easier in that case to use jQuery and simply attach the event handler doing $('.icon').click(function(){ ... }). Of course you are not required to do so.
I recently did something similar where I had a table underneath the feature image of just smaller thumnail images.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You could put the url of the big image in a custom data-attribute on the thumb element, such as <img src="thumb1.png" data-bigsrc="image1.png" />. Then you can add an event to all thumbnails like this:
var thumbs = document.querySelectorAll('.thumbnail');
var mainImage = document.querySelector('#mainImage');
for(var i=0; i<thumbs.length; ++i) {
thumbs[i].addEventListener('click', function(e) {
mainImage.src = e.target.getAttribute("data-bigsrc");
});
}
If you have high quality images and actually want to make them load when the user clicks, you could also use a radio button for each image, with the value set to the URL of the big image. Make the radio buttons invisible and put the thumbnails inside labels. Then you can just bind an event listener to all radio buttons and make them change the main image URL based on the radiobutton value.
Or if you want all the images to load in advance, you should just make tons of big-small image pairs and make the big image only visible if the small image's radiobutton is clicked, making an all-css solution.
As an alternative, this uses vanilla JavaScript, and three different ways of storing/naming the image files are covered.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="divMainImage">
<img id="mainImage" src="/images/image01Main.jpg" alt="Main image" />
</div>
<div id="divThumbnails">
<img class="thumb" src="/images/image01.jpg" alt="image01 thumbnail" />
<img class="thumb" src="/images/image02.jpg" alt="image02 thumbnail" />
<img class="thumb" src="/images/image03.jpg" alt="image03 thumbnail" />
</div>
<script type="text/javascript">
// Name both small and large images the same but with a prefix or suffix depicting thumbnail/main:
// image01.jpg (image01small.jpg) or image01Main.jpg (image01.jpg)
// image02.jpg (image02small.jpg) or image02Main.jpg (image02.jpg) etc.
// Or use two folders - one with main images, the other with thumbnails - both files named the same,
// then swap the folder to use when getting the image.
// Then use the displayed thumbnails' class to load originals:
var thumbnails = document.getElementsByClassName("thumb");
var mainImage = document.getElementById("mainImage");
for (index in thumbnails)
{
thumbnails[index].onclick = function () {
// Depending on the way used use on of the following:
mainImage.src = this.src.replace('.jpg', 'Main.jpg');
// Or
// mainImage.src = this.src.replace('thumb.jpg', '.jpg');
// Or
// mainImage.src = this.src.replace('/images/small/', '/images/large/');
}
}
</script>
</body>
</html>

Switching image with Next/Previous buttons

Is there any way to switch images using next/prev buttons with jQuery? Here's the code:
<div class="prevDiv">
<img src="images/prev.png" alt="previous" />
</div>
<div class="pic" id="picwebd">
<img src="images/portfolio/webdesign/webd1.jpg" class="portPic" />
</div>
<div class="nextDiv">
<img src="images/next.png" alt="previous" />
</div>
I tried modifying this code to my needs: http://jsfiddle.net/x5mCR/16/ but I haven't succeed. I think that incrementing and decrementing number in the image src would be enough, but I can't come up with decent code do this. Google doesn't help neither.
In case anyone reading this post want a different approach still using JQuery fadeIn, Im posting below the code for that.
Here you can find the fiddle for it.
Here's the Javascript Part
//At the start will show the first image
$('#fullimage img.fullimage:first-child').fadeIn();
//Keep track of the image currently being visualized
var curr = $('#fullimage img.fullimage:first-child');
$('#next').on('click', function() {
//Hide Current Image
curr.hide();
//Find Next Image
var next = curr.next();
//If theres no next image (is the last img), go back to first
if (next.length == 0) next = $('#fullimage img:first');
//Fade In
next.fadeIn();
//Save in curr the current Image
curr = next;
return false;
});
$('#prev').on('click', function() {
curr.hide();
var prev = curr.prev();
if (prev.length == 0) prev = $('#fullimage img:last');
prev.fadeIn();
curr = prev;
return false;
});
Here's the HTML part
<div id="fullimage">
<img class="fullimage" src="http://i.imgur.com/RHhXG.jpg" />
<img class="fullimage" src="http://i.imgur.com/p1L2e.jpg" />
<img class="fullimage" src="http://i.imgur.com/NsrI0.jpg" />
<img class="fullimage" src="http://i.imgur.com/Ww6EU.jpg" />
</div>
<label id="prev">previous</label>
<label id="next">next</label>
Here is dynamic and simple script reducing your html code
http://jsfiddle.net/x5mCR/32/
$("#thumbnail a").on('click', function (eve) {
eve.preventDefault();
var link = ($(this).attr("href"));
var content = '<img src="' + link + '"/>';
$("#fullimage").hide().html(content).fadeIn('slow');
});
Remove the anchors with class thumbnail and give the corresponding <img> tags the thumbnail class, then use jQuery click methods for the thumbnail class:
$(".thumbnail").click(function() {
$(".fullimage").src = $(this).attr("src");
});
Make sure you have a single .fullimage in the #fullimage div.
This isn't the same as a next / previous button - but it would fix the JSFiddle that you made.
http://jsfiddle.net/x5mCR/34/
var picNumber = 1;
$(".nextDiv").click(function() {
picNumber++;
if (picNumber > 3) picNumber = 1; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});
$(".prevDiv").click(function() {
picNumber--;
if (picNumber < 1) picNumber = 3; // Change 3 to how many pictures there are.
$(".pic img").attr("src", "images/portfolio/webdesign/webd" + picNumber + ".jpg");
});
If I understand correctly, you're trying to use the arrow keys to move back and forth between pictures...so if this is the case, I would recommend taking a look at this post: Binding arrow keys in JS/jQuery
Also, for your convenience, I just took the code from that post and combined it with the function in your fiddle to get this:
$(document).keydown(function (e) {
if (e.keyCode == 39) {
$(".fullimage").hide();
var next = $(this).next();
if (next.length > 0) {
next.fadeIn();
} else {
$('#fullimage img:first').fadeIn();
}
return false;
}
});
In testing it looks like it might need some modification, and also, you would obviously need to create a similar function for when the back button is pressed, but I think if I'm understanding your issue correctly this is a good starting place.

how to swap image on clicking on image?

Here I use two images. when i click once on the Sort_down.png image then it changes to Sort_up.png.
When I click on this image again it is not changing back to Sort_down.png, how can I achieve this ?
<script type="text/javascript">
function clkimg() {
var img = document.getElementById('stCodeDSC');
img.src = '../Images/sort_up.png';
}
</script>
<td width="11%" bgcolor="#C5DEFF" class="menu_header">
<div align="center" onclick="clkimg();" >
<img name="stCodeDSC" class="img" src="../Images/Sort_down.png" id="stCodeDSC">
</div>
</td>
Depending on the browser you're using, when the source of an image is set to a relative URL, reading it back will give you the absolute URL. If you want to use a toggle, you can check for a string in the source, for example:
function clkimg() {
var img = document.getElementById('stCodeDSC'),
nextImg = img.src.indexOf('up.png')>0 ? 'down':'up';
img.src = '../Images/sort_' + nextImg + '.png';
}
If the sort_up and sort_down images are actually icons just identifying the up or down state of the current sort, you can combine the two images into one and use them as a sprite that you display using CSS. More details will be available at https://stackoverflow.com/search?q=css+sprite
You aren't telling it to sort down. In your click code you'll need to test if the image is showing up or down and change it accordingly. Something like:
if(img.src === '../Images/sort_up.png')
img.src = '../Images/sort_down.png';
else
img.src = '../Images/sort_up.png';
Generally, however, this would be better handled by adding or removing a class on click and styling the class using css.

Categories