Im really new to javascript, and while Im learning, Im trying to change images in a gallery to others with an onclick function.
I have links to different galleries. When I click on link 1, the imgs are one1.jpg, one2.jpg and so on. When I click on link 2, imgs are two1.jpg, two2.jpg, etc.
This is the rough script I made for Link 1:
<script>
function one() {
document.getElementById("foto1").src="one1.jpg";
document.getElementById("foto2").src="one2.jpg";
}
</script>
Link 1
Link 2
<img id="foto1" src="tre1.jpg"></a>
<img id="foto2" src="tre2.jpg"></a>
etc.
I made another function called two() for the second link with same content but changing src to what I want. And for every link I add, I copy the script and change it a little.
I know there is a way to optimize to a single script with variables or something .
Any help?
Thanks
In order to differentiate group of images there must be a pattern.
try to add a class on each img tag to differentiate images for changing their source, and the you can loop through images as follows:
Link 1
Link 2
<img class="img1" id="foto1" src="foto1.jpg">
<img class="img1" id="foto2" src="foto1.jpg">
<img class="img2" id="foto3" src="pic1.jpg">
<img class="img2" id="foto4" src="pic2.jpg">
<script>
function one() {
var img = document.getElementsByClassName("img1");
for (var i in img) {
img[i].src = "foto" + 1 + ".jpg"
}
}
function two() {
var img = document.getElementsByClassName("img2");
for (var i in img) {
img[i].src = "pic" + 1 + ".jpg"
}
}
</script>
Related
So I have a simple slideshow using JavaScript to fade images in and out, where all but one of the img elements do not have a href attribute. I would like to put the href attribute of the image into the href attribute of the caption (actually the img alt attribute) so that the text is clickable when the particular slide shows up, and becomes unclickable when the slide goes to the next one. I am very inexperienced in JS and cannot find any resources online to help me with this particular issue. Here is the part of my HTML file (called Finley.html) that is used, and my slideshow.js file.
<section>
<!-- Slideshow -->
<h2 id="caption">Car ride home! First time meeting each other.</h2>
<img id="slide" src="images/Finley/car_ride_home.jpg" alt="">
<div id="slides">
<img src="images/Finley/car_ride_home.jpg" alt="Car ride home! First time meeting each other.">
<img src="images/Finley/he_lay.jpg" alt="Handsome boy!">
<img src="images/Finley/awwww.jpg" alt="First photo together">
<img src="images/Finley/photogenic_af.jpg" alt="Papa, we made it to the community Instagram!" href="https://google.com" target="_blank">
<img src="images/Finley/first_vet.jpg" alt="First vet trip was successful">
<img src="images/Finley/blop.jpg" alt="blop.">
<img src="images/Finley/squishy_cheek.jpg" alt="Car rides make me sleepy">
<img src="images/Finley/first_beach.jpg" alt="First time at the beach and I got rocked by the waves">
<img src="images/Finley/sploot.jpg" alt="sploot.">
<img src="images/Finley/floopy_ears.jpg" alt="My family loves how floopy my ears are!">
<img src="images/Finley/daisy_gf.jpg" alt="Playing with my friend Daisy!">
</div>
</section>
slideshow.js:
$(document).ready(function() {
//declare variables
var nextSlide = $("#slides img:first-child");
var nextCaption;
var nextSlideSource;
// the function for running the slide show
var runSlideShow = function() {
// write the function
$("#caption").fadeOut(1000);
$("#slide").fadeOut(1000,
function() { //callback function
if (nextSlide.next().length == 0) {
nextSlide = $("#slides img:first-child");
} else {
nextSlide = nextSlide.next();
}
nextSlideSource = nextSlide.attr("src");
nextCaption = nextSlide.attr("alt");
if (nextCaption == "Papa, we made it to the community Instagram!") {
$("#caption").attr("href", nextSlide.attr("href"); $("#caption").attr("target", nextSlide.attr("target");
}
$("#slide").attr("src", nextSlideSource).fadeIn(1000); $("#caption").text(nextCaption).fadeIn(1000);
}
); //callback
}; //ready
// start slide show
var timer1 = setInterval(runSlideShow, 5000);
// here's one way to code this app without using the toggle event method
$("#slide").click(function() {
if (timer1 != null) {
clearInterval(timer1);
timer1 = null;
} else {
timer1 = setInterval(runSlideShow, 1000);
}
});
})
This code displays the caption as text above the image, and the image stays on screen for 5 seconds before fading to the next image. To clarify, I'd like the caption text that appears to become a hyperlink to Google (actual site censored) for the one picture when it is displayed, and then return to normal once the next picture comes up. I tried putting line 21-24 in to test for the caption and set the attribute, but those lines stop the slideshow from working (remove those lines to see how it should behave). Maybe it's something in the if statement in line 21, but I'm not sure how to proceed. Any help or tips would be appreciated!
You can do it either like this:
this.hasAttribute('href');
or
$(this).is('[href]');
More Info
I have a script that plays a video in a Modal when a thumbnail gets clicked. This only works with the first video mentioned in the html, so I'm trying to use js to grab the particular video whos thumbnail is clicked on.
I have set up a variable in the js called vidcode, and gave it a value of the first video's address (rLdpnu2dDUY) or whatever it's called. I then set up a value 'start' for the link part before, and 'end' for the link part after. Now I have "showVideo = start + vidcode + end" and then innerHTML = showVideo, which works no problems.
So far the injection part works. My problem now is passing the address of the clicked thumbnail into the vidcode variable to play the corresponding video. I have looked on SO, w3, and Google. I have 6 different tries and none work fully.
I can create a link which
- Sets the variable, but then does not call the script.
- Calls the script but does not pass on the variable.
- Click one thumb to set the variable then another thumb to call the script. That one will then work but it's an extra step. At least with this one I know that the variable is being set..
<!--== Standard button but requires var vidcode to be preset in the Modal script ==-->
<img src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<!--== Add onClick to trigger a mini-script which sets the var vidcode early ==-->
<script>function hDSansxhArU(){var vidcode = 'hDSansxhArU';}</script>
<!--== Adding the javascript directly to the link code, yet it does not trigger the Modal script ===-->
<!--== Adding the javascript directly to the link code, to trigger a mini-script, to then call the modal ===-->
<script>function buttt(){var vidcode = 'duBjWlIzpzQ'; modalviewer();}</script>
<!--== Use the video's code as an id, then calling that id immediately and setting it to var vidcode ==-->
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer()
};
</script>
Spots are commented out when trying something else
function modalviewer(){ //This function usually isn't here
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
//var showVideo = start + vidcode + end;
// This part works fine when vidcode gets a value
document.getElementById("button").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = showVideo;
document.querySelector(".bg-modal").style.display = "flex";
});
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
};
Expected results:
Click a link and have either
- set that address to variable 'vidcode', or
- set the address gobbledegook to 'vidcode' from here
and either have the modal script in a separate js file or at the bottom of the page.
As a code-newbie, I'm proud to have figured it out so far (with previous help from SO), it just frustrates me that I can only get half of this to work at a time :/.
#CTOverton provided what was needed, although everyone else and in Stop/Pause video when Modal is closed (not using $ sign) contributed with everything that they got me to look up as well. #Phoenix1355 actually started me on the right path despite me not posting any code at all, in turn leading me to learn so much in very little about Javascript and HTML.
This has been plaguing me for at least a week (I've lost track of time making this website), researching, getting other setups, trying overly-complicated setups, being told it can only be done by paying for a hosting plan or having to use Wordpress.. And this Console.log output, sooo helpful omg. Thank you everyone who contributed!
Here is the finished code:
<html>
<head>
<link href="http://www.jolanxbl.ca/snips/modal.css" rel="stylesheet" />
</head>
<body>
<center>
<br><br><br><br><br>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg" width="200px">
<img data-vidcode="hDSansxhArU" src="https://img.youtube.com/vi/hDSansxhArU/hqdefault.jpg" width="200px">
<img data-vidcode="duBjWlIzpzQ" src="https://img.youtube.com/vi/duBjWlIzpzQ/hqdefault.jpg" width="200px">
</center>
<!-- Modal Section 1 -->
<div class="bg-modal">
<div class="modal-content">
<div class="close">+</div>
<div class="theVideo">
<iframe width="840" height="472" src="https://www.youtube.com/embed/rLdpnu2dDUY" frameborder="0" encrypted-media; picture-in-picture allowfullscreen></iframe>
</div>
</div>
</div>
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
//document.querySelector(".gridContainer").addEventListener("click", function() {
document.querySelector(".theVideo").innerHTML = '<iframe width="840" height="472" src="https://www.youtube.com/embed/' + vidcode + '" frameborder="0" encrypted-media></iframe>';
document.querySelector(".bg-modal").style.display = "flex";
}
document.querySelector(".bg-modal").addEventListener("click", function() { //.bg-modal to make the surrounding clickable
document.querySelector(".bg-modal").style.display = "none";
document.querySelector(".theVideo").innerHTML = "";
});
</script>
</body>
</html>
Based on your description I think you are looking for something along the lines of the "data attribute". Data attributes are custom attributes you can assign to any DOM element that contain essentially whatever you want.
In you case if you have a page with lots of thumbnails and you want a specific action to happen when you click on a specific thumbnail, your best bet is if you store that unique identifier (the video id, or are you put it vidcode) on the element you are clicking on.
This can be done like this:
<body>
<!--List of videos-->
<img data-vidcode="rLdpnu2dDUY" src="https://img.youtube.com/vi/rLdpnu2dDUY/hqdefault.jpg">
<img data-vidcode="example2" src="img2.jpg">
<img data-vidcode="example3" src="img3.jpg">
<script>
let vidcode = 'rLdpnu2dDUY';
// Get all elements with classname 'thumbnail'
let thumbnails = document.getElementsByClassName('thumbnail');
// Loop for every element with class
Array.from(thumbnails).forEach(function(element) {
element.addEventListener('click', thumbnailClicked);
});
function thumbnailClicked(event) {
// Event is mouse click event
// target is the img (as that is what you click on)
// dataset is the data attributes of img
vidcode = event.target.dataset.vidcode;
console.log('vidcode: ', vidcode)
}
</script>
</body>
Try passing the vidcode as an parameter for modalviewer function and then use the value.
function modalviewer(vidcode){
var start = '<iframe width="840" height="472" src="https://www.youtube.com/embed/';
var end = '" frameborder="0" encrypted-media></iframe>';
var showVideo = start + vidcode + end;
document.querySelector(".theVideo").innerHTML = showVideo;
};
<div class="theVideo"></div>
Click
<script>
document.getElementById('hDSansxhArU').onclick = function() {
var vidcode = 'hDSansxhArU';
modalviewer(vidcode)
};
</script>
I'm learning Javascript for my Intro to Programming Concepts class and I decided to make a simple photography portfolio site for my final project. I'm making the gallery now and I'm not sure how swap images.
This is what it looks like (cut off but you get the idea):
screenshot
This is the HTML:
<div id="gallery">
<div>
<img src="images/nature/1.jpg">
<br>
<div class="gallery">
<img src="images/nature/2.jpg">
<img src="images/nature/3.jpg">
<img src="images/nature/4.jpg">
<img src="images/nature/5.jpg">
<img src="images/wedding/1.jpg">
<img src="images/wedding/2.jpg">
<img src="images/wedding/3.jpg">
<img src="images/wedding/5.jpg">
<img src="images/wedding/4.jpg">
</div>
</div>
</div>
How do I make it so when you click an img from .gallery it swaps places with the first img (images/nature/1.jpg)?
The following should take whatever image is currently in the first image and swap it out with the one that is clicked:
var firstImage = document.getElementsByTagName('img')[0],
gallery = document.getElementsByClassName('gallery')[0];
gallery.addEventListener('click', function(e) {
var target = e.target;
if (target.tagName == "IMG") {
var newImage = target.src;
target.src = firstImage.src;
firstImage.src = newImage;
}
});
You can test it out here: https://jsfiddle.net/hxhe90qL/6/
After enough clicking around, however, the images will probably be all out of order. You could change it to only swap the first image by replacing the code inside the if statement to:
firstImage.src = target.src;
I think you mean when you click on swipe div, no matter what pic is showing in .gallery will be replaced by 1.jpg.
If that is the case, you can bind onclick event on .gallery, by getting event object, you can get access to the source dom element that triggers the event.
Then you can use javascript to change src attribute.
var gallery = document.querySelector('.gallery');
gallery.addEventListener('click', function(e) {
var targetImg = e.target;
targetImg.src = 'images/nature/1.jpg';
});
I'm new to Java and need to build an image gallery.
I have a catalogue of images: each category has a thumbnail; each category has three images.
Process:
Click on thumbnail, bigPic changes its src to show the image you clicked on.
Three dots below bigPic can be clicked to see the other images in that category (so if another thumbnail is chosen, the srcs they pass onto bigPic will change too)
I have tried a few things and looked around but I cannot seem to make it work.
Here is what I have so far:
<script>
function backColor(a) {
document.getElementById("bigPic").src = a;
}
function varE(e){
var chosen = e;
document.getElementsByName("firstDot").id = chosen;
}
function setM(m) {
var chosenImage = m.id;
document.getElementById("bigPic").src = chosenImage;
}
</script>
bigPic:
<img class="bigPic" id="bigPic">
thumbnail image:
<img class="thumb" src="categoryImageSRC" onclick="backColor('anotherImageSRC'); varE('otherImageSRC')">
dot/circle that shows another image in category:
<img name="firstDot" id="" src="dotImageSRC" onclick="setM(this)">
Any ideas on how to go about this, examples and corrections are very welcome! Thank you!
get element by name returns an array of element so you need to change this line in varE function
document.getElementsByName("firstDot").id = chosen;
to
document.getElementsByName("firstDot")[0].id = chosen;
I can't create simple gallery photos. After click to small image I need reload image in place for main image.
gallery.js
imgArray = [
'../images/1.jpg',
'../images/2.jpg',
'../images/3.jpg',
'../images/4.jpg',
'../images/5.jpg',
'../images/5.jpg'
];
function changeImage(nameOfImage){
document.getElementById('mainImage').src = imgArray[nameOfImage.id];
}
html
<div align="center" class="mainImageDiv">
<img id="mainImage" src="images/action/1.jpg" alt="1.jpg, 206kB" title="1" height="600" width="500">
</div>
<img src="images/action/min1.jpg" alt="min1.jpg, 18kB" title="min1" height="120" width="100" />
<img src="images/action/min2.jpg" alt="min2.jpg, 18kB" title="min2" height="120" width="100" />
Something like this is the code you need:
http://jsfiddle.net/M2BSu/
var imgArray = [
'http://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Brain_human_sagittal_section.svg/295px-Brain_human_sagittal_section.svg.png',
'http://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Solanum_muricatum_Flower_and_Fruit.jpg/220px-Solanum_muricatum_Flower_and_Fruit.jpg'
];
var counter = 0;
document.getElementById('my_button').onclick = function () {
document.getElementById('mainImage').src = imgArray[counter % imgArray.length];
counter += 1;
}
EDIT It seems I misunderstood the problem. I guess the error is, as people commented, that your id is not a valid array index. You can use a real object instead, like this:
<a href="#" id="a_full_name" onClick="changeImage(this)">
var images = {
'a_full_name': 'path to image',
'another_img_id': 'path to this image'
};
function changeImage(anchor_object){ ... } // what you are passing is not the name of the image
And with that your code should work. Arrays are not very reliable in JavaScript (since they are not real arrays)
EDIT: Once found the problem, I give you this easy solution for your problem. As always, the simpler the better. Don't read any array or whatever, just get the path of the big image, from the path of the small image. You will not have to do any annoying maintenance in parallel of the html and the array. You just have to keep a consistent naming between the thumbnail and the big picture.
html
You don't really need an anchor element. If you want the pointer mouse, change the CSS
<img onClick="changeImage(this)" src="images/action/min1.jpg" title="min1" />
JavaScript
function changeImage(image_clicked){ // you pass the image object
var min_path = image_clicked.src;
// adapt the path to point to the big image, in this case get rid of the "min"
var big_path = min_path.replace("min", "");
document.getElementById('mainImage').src = big_path;
}
Keep it simple.