how to swap image on clicking on image? - javascript

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.

Related

How to change image button on click then get back

I have an image button and I would like to do that if I click to the img button it is changed, then if I click again to the button it change back to the default image.
I have this script but it doesnt change back. Anybody can help me?
<script>
function VOR2(img)
{
if(img.src.match(/blank/))
{
img.src = "VOR.gif";
}
else
{
img.src = "VOR2.gif";
}
}
</script>
<img src="VOR.gif" id="VOR2" onclick=VOR2
The reason that your code is currently not working is because img.src.match(/blank/) looks if the image source has the text "blank" (the forward slashes make it a regex). However neither images you have provided include the text "blank", so it simply does nothing, and isn't the best use case anyways.
The best practice for this would be toggling a class with classList to your image to help identify which "state" it is in, such as the below:
<script>
function VOR2(img) {
isChanged = img.classList.contains('changed-image');
img.src = isChanged ? 'VOR.gif' : 'VOR2.gif';
img.classList.toggle('changed-image');
}
</script>
<img src="VOR.gif" id="VOR2" onclick=VOR2>
I would also suggest moving the script into a different file.
You could do it this way :
JS :
function VOR2(img) {
if (img.src == "VOR2.gif") {
img.src = "VOR.gif";
} else {
img.src = "VOR2.gif";
}
console.log(img.src);
}
HTML :
<img src="VOR.gif" id="VOR2" onclick="VOR2(this)" />

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>

All purpose image swap function

Ok, I am new to JavaScript so please keep that in mind when you answer. What I am looking for is a function that I can use that will enable me to click an image, then click another image and swap their positions on the page. For example I have a 3x4 table with 12 separate images, I click on 'image1' and then click 'image3' and the two swap. The only solutions I have found deal with swapping an image with a specified image, this is not what I need. Hope this makes sense.
Any suggestions and solutions are welcomed to help me learn! Thank you!
Also, I would like this to be 100% JavaScript and not jQuery.
HTML:
<table>
<tr>
<th id="pos1"> <img src="pic_01.gif" id="pic1" onclick="imageSwap()" alt="" border= height=100 width=100></img> </th>
<td id="pos2"> <img src="pic_02.gif" id="pic2" alt="" border= height=100 width=100> </img></td>
<td id="pos3"> <img src="pic_03.gif" alt="" border= height=100 width=100></img></td>
</tr>
Attempted JS:
imgArray[0] = new Image();
imgArray[0].src = 'pic_01.gif';
imgArray[1] = new Image();
imgArray[1].src = 'pic_02.gif';
imgArray[2] = new Image();
imgArray[2].src = 'pic_03.gif';
etc etc...
var a
var b
function imageSwap(){
getElementById.src = a
Not sure at all what to do for the swap itself
So I was bored and felt like being nice, so here's an example of image swapping, even though you made no attempt. Try to avoid being distracted by the cute kittens.
The part of the code that matters is the script:
var position = null,
target = null;
$("img").click(function(){
if ($(this).attr("class") == "border"){
$(this).toggleClass("border");
target = null;
position = null;
return false;
}
else{
$(this).toggleClass("border");
if (position == null){
position = $(this).attr("src");
$(this).toggleClass("position");
}
else{
target = $(this).attr("src");
$(this).attr("src", position);
$(".position").attr("src", target)
.toggleClass("position");
$(".border").toggleClass("border");
position = null;
target = null;
}
}
})
The <html> is just a set of images and the CSS just adds some margins and the border for the image you click. In short, the code checks whether the image has been selected. If it already has a selection border and you click it again, it deselects the image. If the image clicked hasn't been selected, it checks whether a position has been set. If a position has been set, it swaps the target (the image just clicked) with the image previously clicked. Otherwise, it sets the image clicked as the position (and then the next click will cause the images to swap).

append string to image src using js

I've got a page where there is <img src="/images/product/whatever-image.jpg" alt="" />
I want it so that upon loading of the page, the string "?Action=thumbnail" is appended to src's value, making it src="/images/product/whatever-image.jpg?Action=thumbnail"
how do I achieve this using js?
window.addEventListener('load', function(){
/* assuming only one img element */
var image = document.getElementsByTagName('img')[0];
image.src += '?Action=thumbnail';
}, false);
Note, changing the source of the image will "re-fetch" the image from the server — even if the image is the same. This will be better done on the server-side.
Update after comment:
window.addEventListener('load', function(){
/* assuming only one div with class "divclassname" and img is first child */
var image = document.getElementsByClassName('divclassname')[0].firstChild;
image.src += '?Action=thumbnail';
}, false);
Use this:
window.onload = function() {
document.getElementById('myImage').src += "/Action=thumbnail";
};

Change image on click

I have a table and I would like to change an image in its <td> when I click it but it must be URL of image that I determine before.
That URL of image I type to the link of the page(for example by click on img)
index.html?type=dog
Then the script will read variables from link. I will create variable to the script.
type = httpGetVars["type"]
Now when I click on where is img of cat, the script should replace cat.png for dog.png and I tried it in this way.
<img src="cat.png" onClick="document.write("<img src=\""+ type + ".png\">);
<img id="foo" src="cat.png />
Give that <img> an id - foo for example than:
document.getElementById('foo').src = type +".png";
You simply change the existing <img> src to the new image.
You can define the img like the following:
<img src="some_image_url.extension" onclick="switchImage(this)" />​
and then on the switchImage function you can check the current image and change to a different image:
var switchImage = function(image) {
if(image.src == dogImage) {
image.src = catImage;
} else {
image.src = dogImage;
}
};​
I've made a Sample Fiddle so you can see it running.

Categories