Javascript - How to get element that was clicked - javascript

I'm making a really simple photo gallery with thumbnails and I have a working code which changes the big image when a thumbnail is clicked. Now what I need is to add a green border to the thumbnail which is currently active.
HTML:
<div id="gallery">
<div id="big">
<img align="center" src="big/pipe_big.jpg" alt="" id="image" />
</div>
<div id="small">
<img onclick="changeImage('pipe')" src="small/pipe_small.jpg" alt="" />
<img onclick="changeImage('leaves')" src="small/leaves_small.jpg" alt="" />
<img onclick="changeImage('orange')" src="small/orange_small.jpg" alt="" />
<img onclick="changeImage('xuangong')" src="small/xuangong_small.jpg" alt="" />
</div>
<div id="small">
<img onclick="changeImage('grave')" src="small/grave_small.jpg" alt="" />
<img onclick="changeImage('lotus')" src="small/lotus_small.jpg" alt="" />
<img onclick="changeImage('tibet_girl')" src="small/tibet_girl_small.jpg" alt="" />
<img onclick="changeImage('girl_water')" src="small/girl_water_small.jpg" alt="" />
</div>
</div>
JS:
function changeImage(x){
var image = document.getElementById('image');
var active_image = ??????????
if (x == 'pipe') {
image.src = 'big/pipe_big.jpg';
} else if (x == 'leaves') {
image.src = 'big/leaves_big.jpg';
} else if (x == 'orange') {
image.src = 'big/orange_big.jpg';
} else if (x == 'xuangong') {
image.src = 'big/xuangong_big.jpg';
} else if (x == 'grave') {
image.src = 'big/grave_big.jpg';
} else if (x == 'lotus') {
image.src = 'big/lotus_big.jpg';
} else if (x == 'tibet_girl') {
image.src = 'big/tibet_girl_big.jpg';
} else if (x == 'girl_water') {
image.src = 'big/girl_water_big.jpg';
}
active_image.style.border = '2px solid green';
}
So I need to find the element that triggered the function and put it into variable "active_image" so that the function "changeImage()" always changes the border to 2px solid green. And please no jQuery solutions, I need it to be JavaScript.

Are you looking for this?
var images = document.querySelectorAll( "#gallery img" );
for( i =0; i< images.length; i++ ) {
images[i].style.border = "0px";
}
var active_image = event.target;

Just change the function calls to include 'this' as the second parameter:
<div id="gallery">
<div id="big">
<img align="center" src="big/pipe_big.jpg" alt="" id="image" />
</div>
<div id="small">
<img id="img1" onclick="changeImage('pipe',this)" src="small/pipe_small.jpg" alt="" />
<img id="img2" onclick="changeImage('leaves',this)" src="small/leaves_small.jpg" alt="" />
<img id="img3" onclick="changeImage('orange',this)" src="small/orange_small.jpg" alt="" />
<img id="img4" onclick="changeImage('xuangong',this)" src="small/xuangong_small.jpg" alt="" />
</div>
<div id="small">
<img id="img5" onclick="changeImage('grave',this)" src="small/grave_small.jpg" alt="" />
<img id="img6" onclick="changeImage('lotus',this)" src="small/lotus_small.jpg" alt="" />
<img id="img7" onclick="changeImage('tibet_girl',this)" src="small/tibet_girl_small.jpg" alt="" />
<img id="img8" onclick="changeImage('girl_water',this)" src="small/girl_water_small.jpg" alt="" />
</div>
And the dom element will be available in the function. So your function becomes:
var active_element_id;
function changeImage(x,element){
var image = document.getElementById('image');
var active_image = element.src;
if (x == 'pipe') {
image.src = 'big/pipe_big.jpg';
} else if (x == 'leaves') {
image.src = 'big/leaves_big.jpg';
} else if (x == 'orange') {
image.src = 'big/orange_big.jpg';
} else if (x == 'xuangong') {
image.src = 'big/xuangong_big.jpg';
} else if (x == 'grave') {
image.src = 'big/grave_big.jpg';
} else if (x == 'lotus') {
image.src = 'big/lotus_big.jpg';
} else if (x == 'tibet_girl') {
image.src = 'big/tibet_girl_big.jpg';
} else if (x == 'girl_water') {
image.src = 'big/girl_water_big.jpg';
}
if(active_element_id){
var active_element = document.getElementById(active_element_id);
active_element.style.border = '0px solid green';
}
element.style.border = '2px solid green';
active_element_id = element.getAttribute('id');
}

You can add a green border to the element which is currently being hovered over, by using onmouseover and onmouseout as well as this.style.borderColor to change the color:
<img onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'" onclick="changeImage('pipe')" src="small/pipe_small.jpg" alt="" />
Working Example:
div {
border-style: solid;
border-width: medium;
border-color: black;
width: 100px;
height: 100px;
}
<div onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'"></div><br>
<div onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'"></div><br><div onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'"></div><br><div onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'"></div><br><div onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'"></div><br><div onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'"></div><br><div onmouseover="this.style.borderColor='green'" onmouseout="this.style.borderColor='black'"></div><br>

Plunkr Example
The way with least changes to your code:
function changeImage(x){
var active_image = this;
var image = document.getElementById('image');
var images = [],
containers = document.getElementsByClassName('small');
for (var i=0,n=containers.length; i < n; i++){
var imgs = containers[i].getElementsByTagName('img');
for (var j=0,m=imgs.length; j < m; j++ ){
images = images.concat(imgs[j]);
}
}
if (x == 'pipe') {
image.src = 'big/pipe_big.jpg';
} else if (x == 'leaves') {
image.src = 'big/leaves_big.jpg';
} else if (x == 'orange') {
image.src = 'big/orange_big.jpg';
} else if (x == 'xuangong') {
image.src = 'big/xuangong_big.jpg';
} else if (x == 'grave') {
image.src = 'big/grave_big.jpg';
} else if (x == 'lotus') {
image.src = 'big/lotus_big.jpg';
} else if (x == 'tibet_girl') {
image.src = 'big/tibet_girl_big.jpg';
} else if (x == 'girl_water') {
image.src = 'big/girl_water_big.jpg';
}
// reset border
for (var i=0,n=images.length;i<n;i++){
images[i].style.border = '0px solid green';
}
// set active border
active_image.style.border = '2px solid green';
}
Note you cannot have two elements with the same ID (e.g., small), so you must use a class, or change the ID to a unique name.
Also see that if you use the call() method, you can pass along what this is. In this case, it's important because you want to pass along the element that is being clicked. So for onclick="<function name>.call(this)", the this is that element.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="gallery">
<div id="big">
<img align="center" src="big/pipe_big.jpg" alt="" id="image" />
</div>
<div class="small">
<img onclick="changeImage.call(this,'pipe')" src="small/pipe_small.jpg" alt="" />
<img onclick="changeImage.call(this,'leaves')" src="small/leaves_small.jpg" alt="" />
<img onclick="changeImage.call(this,'orange')" src="small/orange_small.jpg" alt="" />
<img onclick="changeImage.call(this,'xuangong')" src="small/xuangong_small.jpg" alt="" />
</div>
<div class="small">
<img onclick="changeImage.call(this,'grave')" src="small/grave_small.jpg" alt="" />
<img onclick="changeImage.call(this,'lotus')" src="small/lotus_small.jpg" alt="" />
<img onclick="changeImage.call(this,'tibet_girl')" src="small/tibet_girl_small.jpg" alt="" />
<img onclick="changeImage.call(this,'girl_water')" src="small/girl_water_small.jpg" alt="" />
</div>
</div>
</body>
</html>
Big Note
There is much more you could do to your code to make it more scalable and efficient, this is only a starter answer, without confusing you too much. Please keep at, keep learning and expanding your knowledge.

You can use this inside an event handler to get the element. However, since you use inline event handlers, inside changeImage, this will be another value (you could still pass it using call, apply, or as an argument).
However, better avoid inline event listeners:
var image = document.getElementById('image'),
images = document.getElementById('small').getElementsByTagName('img');
for(var i=0; i<images.length; ++i)
images[i].addEventListener('click', changeImage);
function changeImage(){
var x = this.getAttribute('data-img');
image.src = 'big/' + x + '_big.jpg';
this.style.border = '2px solid green';
}
<div id="gallery">
<div id="big">
<img align="center" src="big/pipe_big.jpg" alt="" id="image" />
</div>
<div id="small">
<img data-img="pipe" src="small/pipe_small.jpg" alt="" />
<img data-img="leaves" src="small/leaves_small.jpg" alt="" />
<img data-img="orange" src="small/orange_small.jpg" alt="" />
<img data-img="xuangong" src="small/xuangong_small.jpg" alt="" />
<img data-img="grave" src="small/grave_small.jpg" alt="" />
<img data-img="lotus" src="small/lotus_small.jpg" alt="" />
<img data-img="tibet_girl" src="small/tibet_girl_small.jpg" alt="" />
<img data-img="girl_water" src="small/girl_water_small.jpg" alt="" />
</div>
</div>

Related

Random image from html on button click

I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here's my code.
window.addEventListener('load', start, false);
function start() {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('ekran');
var pictures = document.getElementsByTagName('img');
var choose = Math.floor(Math.random()*pictures.length);
butt.addEventListener('click', menjaj, false);
function menjaj(e) {
var new = e.button;
var img = [];
for(var i = 0; i< pictures.length; i++) {
var dodaj = img[i];
img.push(dodaj);
}
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
<body>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
</body>
This is a working snippet of your code:
window.addEventListener('load', start, false);
function start () {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
var pictures = document.getElementsByTagName('img');
butt.addEventListener('click', menjaj, false);
function menjaj (e) {
// var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
// var btn = e.button;// but this line is useless
var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks
var img = document.createElement('img'); //creates new img tag
img.src = pictures[choose].src;
rnImg.innerHTML = ''; //to delete previous image
rnImg.appendChild(img);
// var img = []; //useless lines of code
// for(var i = 0; i< pictures.length; i++) {
// var dodaj = img[i];
// img.push(dodaj);
// }
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
welcome to StackOverflow!
I would first hide the .wrapper > div img as that will prevent the images to show, then, append a data-pos to help select the position and simply randomize them and pick the src to show on the placeholder
and remember that you have a <div> as placeholder, so you can't assign src, only if you change it to <img>
so, something like this 😊
function chooseImg() {
// get total images available
var totalImages = document.querySelectorAll('.wrapper > div img').length
log('totalImages', totalImages)
// get a random position
var rndPosition = Math.floor(Math.random() * totalImages)
log('rndPosition', rndPosition)
// get hold of the image for such position
var rndImage = document.querySelector('.wrapper > div img[data-pos="' + rndPosition + '"]')
log('rndImage', rndImage)
// assign the source to the DIV
document.querySelector('.rndmImage').style = 'background-image: url("' + rndImage.src + '")'
}
function log(txt, obj) {
console.log(txt, obj)
}
.wrapper > div img {
display: none;
}
.rndmImage {
background-size: contain;
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div>
<img data-pos="0" src="https://randomwordgenerator.com/img/picture-generator/54e5d2434953a514f1dc8460962e33791c3ad6e04e507440742f7cd09645cc_640.jpg" alt="leto1">
<img data-pos="1" src="https://randomwordgenerator.com/img/picture-generator/54e2d1404a57a814f1dc8460962e33791c3ad6e04e5074417c2d78d19f44c4_640.jpg" alt="leto2">
<img data-pos="2" src="https://randomwordgenerator.com/img/picture-generator/57e2d5444851a414f1dc8460962e33791c3ad6e04e50744172287ad2914fc4_640.jpg" alt="leto3">
<img data-pos="3" src="https://randomwordgenerator.com/img/picture-generator/51e8d0444f56b10ff3d8992cc12c30771037dbf85254794e722c73d19245_640.jpg" alt="leto4">
<img data-pos="4" src="https://randomwordgenerator.com/img/picture-generator/53e4d2464a56a914f1dc8460962e33791c3ad6e04e507440722d7cd39345c1_640.jpg" alt="leto5">
<img data-pos="5" src="https://randomwordgenerator.com/img/picture-generator/57e9dc434b5ba414f1dc8460962e33791c3ad6e04e50744172297bd5934cc4_640.jpg" alt="leto6">
<img data-pos="6" src="https://randomwordgenerator.com/img/picture-generator/55e1dc4b4254ad14f1dc8460962e33791c3ad6e04e507440722d72d09249c7_640.jpg" alt="leto7">
<img data-pos="7" src="https://randomwordgenerator.com/img/picture-generator/57e9d4474e54a814f1dc8460962e33791c3ad6e04e50744172297cdd974cc0_640.jpg" alt="leto8">
<img data-pos="8" src="https://randomwordgenerator.com/img/picture-generator/53e6dc404951b10ff3d8992cc12c30771037dbf852547848702e7ed19348_640.jpg" alt="leto9">
</div>
<div>
<button type="button" onclick="chooseImg()">choose</button>
</div>
<div class="rndmImage"></div>
</div>
<div class="wrapper">
<img src="../Assets1/Image/1.svg" alt="" />
<img src="../Assets1/Image/2.svg" alt="" />
<img src="../Assets1/Image/3.svg" alt="" />
</div>
<button>Click</button>
<div class="randomImageContainer"></div>
const button = document.querySelector('button');
button.addEventListener('click', randomImage);
function randomImage() {
const image = document.querySelectorAll('.wrapper > img');
const randomImageContainer = document.querySelector('.randomImageContainer');
let randomNumber = Math.floor(Math.random() * image.length);
const img = document.createElement('img');
img.src = image[randomNumber].src;
randomImageContainer.appendChild(img);
}
You can do this with plain javascript like this:
document.querySelector("button").addEventListener("click", () => {
var imgElements = document.querySelectorAll(".wrapper img");
document.querySelector(".rndmImage").innerHTML = imgElements[Math.floor(Math.random() * imgElements.length)].outerHTML;
});
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
If you're able to use randojs, you can even simplify the randomness and make it all cryptographically secure like this:
document.querySelector("button").addEventListener("click", () => document.querySelector(".rndmImage").innerHTML = rando(document.querySelectorAll(".wrapper img")).value.outerHTML);
<script src="https://randojs.com/2.0.0.js"></script>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
Try this:
this is my image in HTML file
<snap id="image" class="btn btn-warning" onclick="changeImage()">Image</snap>
<image id="imagechange" src="https://picsum.photos/200/300" ></image>
my javascript file
imgcount = 0;
function changeImage() {
document.getElementById("imagechange").src =
"https://picsum.photos/200/" + (300 + imgcount);
imgcount++;
}
everytime you click button you get a new image

Target specific class with setInterval and function with jQuery

I've been working with a script to randomly toggle classes on a set of images. So far it works as intended, but the one thing I was wondering if there is a way to target a specific class since it appears to target the window and I'm not sure that the best way to go about it.
Here's what I have so far:
var counter = 0;
$('.images img').each(function(i) {
if (i == 0) {
counter = 0;
} else {
counter++;
}
if (counter < 5) {
$(this).addClass('show');
} else {
$(this).addClass('hide');
}
});
function shuffleRandomLogos(remove, add) {
const logo = $("." + remove).toArray();
const logoLength = logo.length;
const randomNum = Math.floor(Math.random() * logoLength);
const randomLogo = logo[randomNum];
$(randomLogo).removeClass(remove);
$(randomLogo).addClass(add);
}
window.setInterval(function() {
shuffleRandomLogos("show", "hide");
shuffleRandomLogos("hide", "show");
}, 600);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="images">
<img src="https://www.fillmurray.com/200/300" alt="">
<img src="https://www.fillmurray.com/g/200/300" alt="">
<img src="https://www.fillmurray.com/200/300" alt="">
<img src="https://www.fillmurray.com/g/200/300" alt="">
<img src="https://www.fillmurray.com/200/300" alt="">
<img src="https://www.fillmurray.com/g/200/300" alt="">
<img src="https://www.fillmurray.com/g/200/300" alt="">
<img src="https://www.fillmurray.com/200/300" alt="">
<img src="https://www.fillmurray.com/g/200/300" alt="">
<img src="https://www.fillmurray.com/200/300" alt="">
<img src="https://www.fillmurray.com/g/200/300" alt="">
</div>
I've tried to update const logo = $("."+remove).toArray(); to this:
const logo = $(".images img").toArray(); which works but then it starts to break out of first 5 to be shown and starts getting a little crazy.
So not sure what I need to adjust to just have it target the .images img or if there is a better way to go about it.
Here's a link to a demo (CodePen):
https://codepen.io/ultraloveninja/pen/gJRqPM
You don't need to add random classes at first, just call function manually and later in interval. Also remove all .show classes and add only to selected ones.
Also note that you should move preparation variables out of function for faster processing.
var logos, logosLength;
function makeImages(count)
{
for (var i = 0; i < count; i++) {
$('.images').append('<img src="https://via.placeholder.com/200x300.png?text=' + i + '">');
}
logos = $(".images img");
logosLength = logos.length;
}
function shuffleRandomLogos(count)
{
logos.removeClass('show');
for (var i = 0; i <= count; i++) {
let randomLogo = logos[Math.floor(Math.random() * (logosLength - 1))];
$(randomLogo).addClass('show');
}
}
makeImages(20);
shuffleRandomLogos(5);
window.setInterval(function () {
shuffleRandomLogos(5);
}, 600);
.images img {
display: none;
}
.images img.show {
display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="images">
</div>

Image sequence plays and stops on scroll

This image sequence plays automatically but I want the first 7 images are played automatically and the remaining images (8 to 15) are played after one scroll.
How would I do this?
onload = function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0,
j = 0;
var interval = setInterval(function() {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
j++;
if (j === 14) {
clearInterval(interval);
document.getElementsByClassName("d-none")[0].classList.add('d-block');
}
}, 100);
}
#animation img {
display: none;
}
#animation img:first-child {
display: block;
}
.d-none {
display: none
}
.d-block {
display: block;
}
<div id="animation">
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging01.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging02.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging03.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging04.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging05.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging06.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging07.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging08.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging09.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging10.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging11.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging12.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging13.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging14.png" />
<img src="http://jumpingfishes.com/dancingpurpleunicorns/charging15.png" />
</div>
<div class="d-none">
this div is aappear
</div>

how to create 2 side by side auto playing image slideshows

I would like to add another slideshow with different pics right beside this.
My images have different sizes.
<html>
<head>
<style>
.container{
position:relative;
width:100%;
height:300px;
border-radius:5px;
border:1px solid red;
overflow:hidden;
}
</style>
</head>
<body>
<div id="imgGallary" class="container">
<img src="http://www.examiningcalvinism.com/kingdavid.jpg" alt="" width="100%" height="300" />
<img src="http://www.kingjamesbibleonline.org/1611-Bible/1611-King-James-Bible-Introduction.jpg" alt="" width="100%" height="300" />
<img src="http://biblestudyoutlines.org/wp-content/uploads/2012/07/the-triump-of-david-over-king-hadadezer-of-zobah-1024x729.jpg" alt="" width="100%" height="300" />
<img src="http://www.cgu.edu/Images/news/Flame%20Winter12/KJV-BibleBW.jpg" alt="" width="100%" height="300" />
</div>
<script>
(function(){
var imgLen = document.getElementById('imgGallary');
var images = imgLen.getElementsByTagName('img');
var counter = 1;
if(counter <= images.length){
setInterval(function(){
images[0].src = images[counter].src;
console.log(images[counter].src);
counter++;
if(counter === images.length){
counter = 1;
}
},4000);
}
})();
</script>
</body>
</html>
The key concept here is that a slideshow is a region that has some images and the region can be repeated in everywhere in your page, but the JavaScript code should work in a specific region. The code below shows one of some possible solutions.
(function () {
function slideshow(container) {
var imgLen = document.getElementById(container);
var images = imgLen.getElementsByTagName('img');
var counter = 1;
if (counter <= images.length) {
setInterval(function () {
images[0].src = images[counter].src;
console.log(images[counter].src);
counter++;
if (counter === images.length) {
counter = 1;
}
}, 4000);
}
}
slideshow('imgGallary1');
slideshow('imgGallary2');
})();
.container {
display: inline-flex;
}
.sildeshow {
position: relative;
width: 45%;
height: 300px;
border-radius: 5px;
border: 1px solid red;
overflow: hidden;
}
<div class="container">
<div id="imgGallary1" class="sildeshow">
<img src="http://www.examiningcalvinism.com/kingdavid.jpg" alt="" width="100%" height="300" />
<img src="http://www.kingjamesbibleonline.org/1611-Bible/1611-King-James-Bible-Introduction.jpg" alt="" width="100%" height="300" />
<img src="http://biblestudyoutlines.org/wp-content/uploads/2012/07/the-triump-of-david-over-king-hadadezer-of-zobah-1024x729.jpg" alt="" width="100%" height="300" />
<img src="http://www.cgu.edu/Images/news/Flame%20Winter12/KJV-BibleBW.jpg" alt="" width="100%" height="300" />
</div>
<div id="imgGallary2" class="sildeshow">
<img src="http://www.examiningcalvinism.com/kingdavid.jpg" alt="" width="100%" height="300" />
<img src="http://www.kingjamesbibleonline.org/1611-Bible/1611-King-James-Bible-Introduction.jpg" alt="" width="100%" height="300" />
<img src="http://biblestudyoutlines.org/wp-content/uploads/2012/07/the-triump-of-david-over-king-hadadezer-of-zobah-1024x729.jpg" alt="" width="100%" height="300" />
<img src="http://www.cgu.edu/Images/news/Flame%20Winter12/KJV-BibleBW.jpg" alt="" width="100%" height="300" />
</div>
</div>

Clicking on thumbnail changes an unintended main image

When I click on a thumbnail meant to change (img), it changes the main image of (img1) as well.
I would want only AGM thumbnails to change (img), and BLACSBF to change (img1)
Would appreciate any assistance. (:
My Javascript
function changeImage(img) {
document.getElementById("img").src = img.src.replace("_t", "_b");
document.getElementById("img1").src = img.src.replace("_t", "_b");
My HTML
<img src="images/AGM/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick='changeImage(this);'
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
Thank you very much!
You need to pass the targeted image element as a parameter to the changeImage function
function changeImage(img, target) {
document.getElementById(target).src = img.src.replace("_t", "_b");
}
then
<img src="images/AGM/events_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/AGM/events1_t.jpg"
onclick="changeImage(this, 'img');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img src="images/BLACSBF/events1_t.jpg"
onclick="changeImage(this, 'img1');"
onmouseout="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseover="this.style.opacity=0.5;this.filters.alpha.opacity=0.5">
<img id="img1" src="images/BLACSBF/events_b.jpg" width="650">
You might be able to simplify your markup a little more if you attached event handlers directly in JavaScript. This isn't a cross browser method, but it certainly does work. Firstly you could slim down your markup and turn the bigger img elements into classes, instead of having a bunch of unique IDs to worry about:
<img src="images/AGM/events_t.jpg">
<img src="images/AGM/events1_t.jpg">
<img class="img" src="images/AGM/events_b.jpg" width="650">
<img src="images/BLACSBF/events_t.jpg">
<img src="images/BLACSBF/events1_t.jpg">
<img class="img" src="images/BLACSBF/events_b.jpg" width="650">
Then, in your JavaScript, you could cycle through all the img tags that don't have a class attribute, and add your event handlers with addEventListener() ( this is the part that will not work on IE8, but can be easily fixed with a cross browser implementation).
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (!imgs[i].getAttribute('class')) {
//mouseout handler
imgs[i].addEventListener("mouseout", function () {
this.style.opacity = 1;
this.filters.alpha.opacity = 100;
});
//mouseover handler
imgs[i].addEventListener("mouseover", function () {
this.style.opacity = 0.5;
this.filters.alpha.opacity = 0.5;
});
//click handler
imgs[i].addEventListener("click", function () {
var src = this.src.replace("_t", "_b");
var fullImg = siblingByClass(this);
fullImg.src = src;
//traverse siblings till 'img' class is found
function siblingByClass(node) {
var sibling = node.nextSibling;
if (sibling.nodeType === 3 || sibling.getAttribute('class') !== 'img') {
return siblingByClass(sibling);
} else {
return sibling;
}
}
});
}
}
jsFiddle

Categories