Change image within div on image icon click - javascript

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>

Related

Changing picture serveral times by click in HTML with javascript

I need a programm in HTML with javascript which has two pictures that by click changes from picture A to B and from picture B to A and so on. I think I need a loop...
Please Try Following Code
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">
<p>Click the light bulb to turn on/off the light.</p>
You Can Have example here https://www.w3schools.com/js/tryit.asp?filename=tryjs_lightbulb
you can find a good example of what you want to do in here:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb
you just need to tweak it a bit so it will change the images correctly.
I would recommend building a function with variables to store the images name.
<script>
function ChangeImage(){
var picElement1 = document.getElementById('HTMLImgElement1');
var picElement2 = document.getElementById('HTMLImgElement2');
var temp = picElement1.src;
picElement1.src = picElement2.src;
picElement2.src = temp;
}
</script>
In the html just set up 2 images with ID HTMLImgElement1 and HTMLImgElement2.
and a button with an onclick attr that will forward to this function.

Remove image when clicked

Basically, I'm trying to create a game where the goal is to click on images so they disappear.
I've made a function that spawns one image on a random location on the screen. Then I've also made an interval so it spawns 15 images in random locations. Now I want the images to disappear when clicked on.
My thoughts on doing this were to make a "click" function, so if the images are clicked the "img.style.height = '0px';
However, I'm not getting this or anything to work.
Use
<img onclick="this.style.visibility = 'hidden'" src="..." />
if you want to leave the space occupied by the image, otherwise:
<img onclick="this.style.display = 'none'" src="..." />
If you need to remove the image from an array of objects, you need to define a function as well.
In your code:
img.setAttribute("onclick", "this.style.visibility = 'hidden'" );
or
img.setAttribute("onclick", "this.style.display = 'none'" );
After you insert all images in document, define a click listener for all images and hide images on click. A simple example here
function hide(el) {
el.style.display = 'none';
}
var imgs = document.getElementsByTagName("img");
for(let i = 0; i < imgs.length; i ++) {
imgs[i].addEventListener('click', function(e) {
hide(e.target);
});
}
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgYxw854mGOAp8f16evj_WYw_Ph385nUVygQdxHvuD9b3ueJxT0A" id="1" alt="Mountain View 1">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8_MiTkMX9nLJ9udtnwOQekIrQwUQ9KMZiU4fLfI7YhXCyIGZn" id="2" alt="Mountain View 2">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgR4KM-zrVRmfdGPf5bll9vq4uLw7FSLpTmHUf9-RkYZ92Ey8Q" id="3" alt="Mountain View 3">
Your code should change like this
function SpawnW() {
var img = document.createElement("img");
img.setAttribute("style", "position:absolute;");
img.setAttribute("src", "women3.png");
document.body.appendChild(img);
img.setAttribute("onclick", "this.style.display = 'none'");
// pictureNumber++;
}
SpawnW();
Hope this helps you.

Replace img src with js jquery

I have a newsfeed in my CMS that pulls preview images as well as teaser text for the feed. The images are all thumbnails # 75x75px. I wanted to have the preview images much larger, but cannot scale an image that small.
I'm wondering what JS I need to run to replace all the URL's to the original image src.
Have:
Need to change them all to the below - which is just replacing 'thumb' with 'large':
This needs to apply to a whole css class; as it is a newsfeed & there will be new articles
Here's where I'm at:
function replaceImgSrc(img,imgTwo) {
var arr=[img,imgTwo];
for(i=0;i<arr.length;i++)
arr[i].each(
function(i,e) {
theImg=$(this),
theImg.attr("src",
function(i,e) {
return e.replace("_thumb","_large")
}
)
}
)
}
If the newsfeed is wrapped in a class, try this way.
function replaceImg($class) {
$class.find("img").each(function(k, el) {
var newSrc = $(el).attr("src").replace("_thumb", "_large");
$(el).attr("src", newSrc);
});
}
replaceImg($("#newsfeed"));
And in your HTML, wrap the newsfeed code inside an identifiable DIV.
<div id="newsfeed"> {{place newsfeed code in here}} </div>
Try this fiddle jsfiddle.net/bharatsing/wkh6da93/
This will find all images in page and change its src with large image.
$(document).ready(function(){
$("#btnLarge").click(function(){
$("img").each(function(){
var src=$(this).attr("src");
src=src.replace("_thumb","_large");
var src=$(this).attr("src",src);
});
});
});
If the assumption is that you have all img elements in an array var imgArray, then you can iterate thru them and update the src attribute like this:
imgArray.forEach(enlargeImageSrc);
function enlargeImageSrc (image) {
image.src = image.src.replace('_thumb', '_large');
}
Try this hovering over the button will make the images with class="show" bigger, as soon as you remove the mouse they are small again.
$("button").mouseenter(function (){
var srcI = $(".show").attr("src");
srcI = srcI.replace("thumb","large");
$(".show").attr("src",srcI);
});
$("button").mouseleave(function (){
var srcI = $(".show").attr("src");
srcI = srcI.replace("large","thumb");
$(".show").attr("src",srcI);
});
button{
display:block;
}
img.show{
max-width:400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button>Click me</button>
<img class="show" src="http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png"/>
</div>
I make a code for you where I take two variables one for large image URL and one for small image URL. I create a function on click on change image button your image url change to big image and it show you big image and then you again click on that button it change big image to small image. You can also see the live demo of this here https://jsfiddle.net/Arsh_kalsi01/3s1uudhe/2/
$(document).ready(function(){
var big_image = "http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_large.png";
var small_image = "http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png";
$(document).on("click",".Changeimagetolarge",function(){
var obj = $(this);
obj.removeClass('Changeimagetolarge');
obj.addClass('Changeimagetosmall');
obj.next("img").attr('src',big_image);
});
$(document).on("click",".Changeimagetosmall",function(){
var obj2 = $(this);
obj2.removeClass('Changeimagetosmall');
obj2.addClass('Changeimagetolarge');
obj2.next("img").attr('src',small_image);
});
});
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<div>
<button class="Changeimagetolarge">
Change Image
</button>
<img src="http://cdn4.sportngin.com/attachments/news_article/7560/0742/Screen_Shot_2017-01-04_at_11.30.31_AM_thumb.png">
</div>

Automatically load an image using javascript

I'm using this code to build a gallery:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
[].forEach.call(image,function(x){
x.onmouseover = function(){
mainImage.src = x.src;
};
});
}
The code loads different thumbnails on the big image when "onmouseover". Now I would like to "preload" the first image from that gallery of thumbnails. I tried using onload with
rr_lrg_img.src=document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img')[0].src
but then it conflicts with the onmouseover. Any ideas? I can only use javascript, no jquery.
Since your var image is actually a collection of images, you need to use the [0] index pointer to target the first one:
window.onload=function(){
var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
var mainImage = document.getElementById('rr_lrg_img');
mainImage.src = image[0].src; // Add this line (preload first image into main one)
function toMainImage() {
mainImage.src = this.src;
}
[].forEach.call(image,function(x){
x.addEventListener("mouseenter", toMainImage, false);
});
}
.thumbnails img{height:50px;}
<img src="//placehold.it/200x200&text=default" id="rr_lrg_img">
<div class="thumbnails">
<img src="//placehold.it/200x200/cf5&text=1">
<img src="//placehold.it/200x200/f0f&text=2">
<img src="//placehold.it/200x200/444&text=3">
</div>

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