Change image on click - javascript

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.

Related

Refresh image element after altering src with base64

I'm using jquery cropbox for a little project.
First the <img> is a default image, then i do a upload and FileReader for changing the image to a locally stored image.
like this
$('#selectfiledialog').change(function(evt){
var tgt = evt.target || window.event.srcElement,
files = tgt.files;
if (FileReader && files && files.length) {
var fr = new FileReader();
fr.onload = function () {
$('#the_image').attr('src', fr.result);
}
fr.readAsDataURL(files[0]);
}
});
However, when i will start the croping function on this image, it has the old values of the default image here, a 500x500 image.
So, when I will do the croping it has not got the new specs.
How can i now refresh that img element based on the new src? "add '?' + Math.random();" or date string is the only thing I've found but the new url is base64 encoded so that will not work.
Any ideas?
1 . Create a container for the image before all;
2 . Delete the image and add another image in the container you created.
Note: If you do this you will lost references to the element of the image because it'll be removed. Avoid making continued references to the image, var img = $('#the_image'), i.e.
Your HTML should be similiar to:
<div id="img_container">
<img id="the_image" src=""/>
</div>
Change the script line:
$('#the_image').attr('src', fr.result);
to:
$('#the_image').remove();
$('img_container')append('<img id="the_image" src="' + fr.result + '"/>');

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>

Change Image OnClick & OnMouseover

I am a complete nub with JS, but I fiddle with it occasionally when necessary. I am writing a function that changes two images on a page (before & after gallery images) when a sliding image is click / selected from a marquee below them. I have that working. The problem is that I also need to change the AFTER image when the BEFORE image is moused over, and I dont seem to be able to pass that variable to the function correctly - here is what I have:
<script>
function changeImage(imgName)
{
var img = imgName;
img += 'a.jpg';
var img1 = imgName;
img1 += 'b.jpg';
image = document.getElementById('imgDisp');
image.src = img;
image = document.getElementById('imgDisp1');
image.src = img1;
}
function swap1(image)
{
var img = 'newgallery/';
img += image;
img += 'b.jpg';
image = document.getElementById('imgDisp');
image.src = img;
}
function swap2(image)
{
var img = 'newgallery/';
img += image;
img += 'a.jpg';
image = document.getElementById('imgDisp');
image.src = img;
}
</script>
<table border=0 width=85%>
<tr>
<td align=center valign=top>
<img id="imgDisp1" src=newgallery/1b.jpg height=80
onmouseover="swap1(img)"
onmouseout="swap2(img)"
>
<p class=content>BEFORE</b></p></td>
<td width=35></td>
<td align=center><img id="imgDisp" src=newgallery/1a.jpg width=550></td>
</tr>
</table>
<marquee behavior="scroll" direction="left" scrollamount="3" onMouseOver="this.stop();" onMouseOut="this.start();">
<?php
$imagenum = '1';
$imageset = 'a.jpg';
$imagesetalt = 'b.jpg';
while($imagenum < 37){
$imagename = "$imagenum$imageset";
$imagethumb = "$imagenum$imagesetalt";
if($imagenum == '13'){
}else{
echo"
<img src=\"newgallery/$imagename\" height=\"120\" border=0 onclick=\"changeImage('newgallery/$imagenum')\">
<img src=images/spacer.gif width=25 height=1>";
}
$imagenum++;
}
?>
I can change the images on click in the marquee calling the changeImage function because I can pass the assigned image name variable to the function. I cannot seem to figure out how to pass the BEFORE thumbnail image name variable to the mouseover functions (swap1) & (swap2) respectively. This may just be a simple syntax solution - but again I dont know JS well enough to figure it out - any assistance would be appreciated.
Honestly, your code is a little overcomplicated. You can simplify this by taking advantage of the data attribute of HTML elements.
Lets say you have a container defined as
<div id = 'img_container' class = 'some_class'>
<img id = 'image' class = 'some_image_class' src = '/path/to/default/image.jpg'
data-alt = '/path/to/hover/image.jpg' />
</div>
You can define a function to retrieve the path stored in the data attribute and swap the data and source values via
function swap(image){
//temporary variable to hold the alternate image path
var newImage = image.data("alt");
//store the image src attribute in the `data-alt` attribute
image.data("alt", image.attr("src");
//replace the image src attribute with the new image path
image.attr("src", newImage);
}
Now, you can apply events to the image via
$("#image").on("mouseover", function(e){
swap($(e.currentTarget));
})
.on("mouseout", function(e){
swap($(e.currentTarget));
});
This will allow you to replace the onmouseover and onmouseout events in your HTML.

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";
};

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