Edit: Sorry if I reply late to any solutions because I need time to figure out how they work haha
I am a beginner in Javascript and I am currently trying to use this piece of code to change an image on mouseover
// Mouseover change (Ciel):
function rollover(my_image){
my_image.src = "images/ci2_a.png";
}
function mouseaway(my_image){
my_image.src = "images/ci_a.png";
}
and this is the corresponding HTML
<img src="images/ci_a.png" onmouseover="rollover(this)" onmouseout="mouseaway(this)" alt="xxx" style="float:left; width:38%">
This works fine, but I want to do it for more than one image on the same page (a different image rollover for each picture) . Even after changing the name of the functions and stuff it doesn't work. The first image stops changing onmouseover immediately when I try to add a similar function for the next image. Could someone tell me how to perform similar events on more than one image (not concurrently)? Thank you!
You could add event listeners to all the image elements you'd like.
<img class="my-image" src="images/ci_a.png" onmouseover="rollover(this)" onmouseout="mouseaway(this)" alt="xxx" style="float:left; width:38%"/>
function rollover(){
this.src = "images/ci2_a.png";
}
function mouseaway(){
this.src = "images/ci_a.png";
}
const myImages = document.querySelectorAll('.my-image')
myImages.forEach(img => {
img.addEventListener('mouseenter', rollover)
img.addEventListener('mouseleave', mouseaway)
})
You can send the image file as the second parameter like this:
function rollover(element, image) {
element.src = image
}
...
<img onmouseover="rollover(this, 'images/ci2_a.png')" ...>
But my question is why do you need JavaScript for that? You can use a simple CSS to achieve this.
Since you need different images on load and on hover, you need a single way to define this functionality across a collection of images.
Building on Matthew's approach, here's a way to do that.
JSFiddle to test it real-time.
You'll dynamically generate the images using data attributes to store the alternate (hover) image URL.
<img class="pics" src="https://picsum.photos/id/0/100"
data-swap="https://picsum.photos/id/10/100">
<br>
<img class="pics" src="https://picsum.photos/id/1/100"
data-swap="https://picsum.photos/id/11/100">
<br>
<img class="pics" src="https://picsum.photos/id/2/100"
data-swap="https://picsum.photos/id/12/100">
<br>
<img class="pics" src="https://picsum.photos/id/3/100"
data-swap="https://picsum.photos/id/14/100">
Then define the event listeners for all elements with the class pics. Here's a list of all the events that can be referenced.
On mouseover, store the original image in a data element original.
Then change the src with the value of the data-swap.
On mouseout, replace the src with the original value.
const myImages = document.querySelectorAll('.pics')
myImages.forEach(img => {
img.addEventListener('mouseover', function () {
img.dataset.original = img.src;
img.src = img.dataset.swap;
});
img.addEventListener('mouseout', function () {
img.src = img.dataset.original;
});
})
Related
For some reason, when I use the attribute onload on my img tag, it causes my images to flicker. Ideally, when I load the page, an image is displayed and when I refresh the page, the image is changed.
Here's my tag as well as the function for it:
HTML
<img id="randomimage" onload="randomImg()" src="images/carmainpic.jpg" alt="main pic of car"/>
JavasScript
function randomImg(){
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
Because the function you're calling changes the image's src to a random pick from the array, triggering a new load event, which changes the src randomly again, etc. On at least some browsers the cycle probably stops when you happen to assign the URL the image already has, too.
If your goal is to just show one of those images, at random, you can do that by leaving src off the img entirely and then adding it (once) with script (either immediately following the img in order to avoid your layout having to be adjusted when you add it, or in script at the end of the page if you prefer; no need to wait for any event):
<img id="randomimage" alt="main pic of car"/>
<script>
(function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random() * images.length); // <== Note change, so adding images to the array Just Works
document.getElementById("randomimage").src=images[num];
})();
</script>
Even if you put the script immediately after the <img ...> tag, the img element will be available to the script. So your choice whether to do it inline or with the other scripts at the end of the page.
The randomImg function is called every time the image loads. You can use a flag variable to make sure that you only change the image once:
var changed = false;
function randomImg(){
if (!changed) {
changed = true;
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
}
The problem is that you are listening to the load event on the image, instead of the page.
onload="randomImg()"
So, as soon as the first image loads, it triggers the function randomImg which causes change of src attribute on the image. So the browser will attempt to assign a new image to the element, and yet another load event is triggered, which repeats the entire cycle.
Instead, if you want to choose a random image when the page loads, you can listen to DOMContentLoaded event on the document, and choose a random image.
document.addEventListener("DOMContentLoaded", function() {
var images=["images/carmainpic.jpg","images/carmainpic2.jpg","images/carmainpic3.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
console.log("Showing: " + images[num]);
});
<img id="randomimage" src="images/carmainpic.jpg" alt="main pic of car"/>
Note: Since you are selecting a random image, it is not guaranteed that you will always get a different image when the page is refreshed. Instead, if you must get a different image on refreshing the page, you can perhaps persist the image identifier in localStorage, and use that to determine the next image to display.
Well you can use $(document).ready(function(){}) to do that. Because you want when charge the page that function execute it.
$(document).ready(function(){
function randomImg(){
var images=["https://www.bensound.com/bensound-img/romantic.jpg","https://www.psdstack.com/wp-content/uploads/2016/10/featured-copyright-free-mages.jpg","http://shaebaxter.com/wp-content/uploads/2015/04/Life-of-Pix-free-stock-photos-sea-peaople-water-waves-back-Sunset-Joshua-earle-1024x682.jpg"];
var num=Math.floor(Math.random()*3);
document.getElementById("randomimage").src=images[num];
}
randomImg();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="randomimage" src="" alt="main pic of car"/>
Hello sorry for maybe a stupid question but i can't seem to find a easy solution.
The meaning of my exercise is to put 3 thumbnails on my website, but when I move over the images they need to expand in size (so i have a thumbnail version of the picture and the normal size). The normal size picture has to be on the
<p id="groot"></p>
This do work correctly, the only problem is that the pictures keep showing up when i move over it. So when I move out of the thumbnail the picture need to dissapear. Is there a function or something that get the site to the original state or any solution? Thanks in advance. I hope I explained it clearly.
This is my first question on stackoverflow, so if you have tips for a complete noob :)
This is the body of my HTML code:
<body>
<p><img id="foto1" src="images/thumb-bones.jpg" alt="bones"/>
<img src="images/thumb-castle.jpg" alt="castle"/>
<img src="images/thumb-mentalist.jpg" alt="mentalist"/>
</p>
<p id="groot"></p>
</body>
This is the JS code:
addEventListener("load", init, false);
function init() {
let foto1 = document.getElementsByTagName("img")[0].addEventListener("mouseover", actie, false);
let foto2 = document.getElementsByTagName("img")[1].addEventListener("mouseover", actie2, false);
let foto3 = document.getElementsByTagName("img")[2].addEventListener("mouseover", actie3, false);
foto1.addEventListener("click", uit, false);
}
function actie(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = 'images/image-bones.jpg';
plaats.appendChild(element);
}
function actie2(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = 'images/image-castle.jpg';
plaats.appendChild(element);
}
function actie3(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = 'images/image-mentalist.jpg';
plaats.appendChild(element);
}
Use a mouseout handler and, in the handler, remove all children from that element. An easy way to do that is to assign "" to innerHTML. So for instance:
function actie_off(event) {
document.getElementById("groot").innerHTML = "";
}
Hook that up to all three thumbnails.
If you don't want to use innerHTML, this question's answers give alternatives.
You might consider mouseenter and mouseleave instead of mouseover and mouseout. Probably doesn't make much difference here, it's just that mouseover repeats as the mouse moves across the thumbnails, and the bubbling of mouseout can be confusing with nested elements (not currently relevant for you). See the links for details.
Another thing to consider is to store the fullsize image URL on the thumbnail img elements as a data-* URI, like this:
<img id="foto1" src="images/thumb-bones.jpg" alt="bones" data-fullsize="images/image-bones.jpg"/>
Then you can use a single handler for all of your img elements instead of three separate ones:
function actie(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = this.getAttribute("data-fullsize"); // Getting the fullsize URL
// from the image the event
// relates to
plaats.appendChild(element);
}
I'm trying to create a very simple, pure JavaScript image gallery where upon clicking on a smaller image thumbnail, it changes the larger preview image to the thumbnail you just clicked.
I'm new to JavaScript and i've been experimenting with it a bit. I'm also trying to avoid using onClick within the HTML as I've been told that's bad practice. So I've found that using the addEventListener seems to be another approach.
The only problem is, that i'm not sure what to do with it. Most of the other tutorials use the onClick function which isn't ideal.
I was wondering if anyone could help or even provide some other sources to give me a start.
Here is the HTML and my start at the JavaScript:
HTML
<section class="image-gallery">
<h4>IMAGE GALLERY</h4>
<section id="gallery-preview">
<img src="images/gallery1.png" alt="image-gallery-1">
</section>
<section id="gallery-thumbnails">
<img src="images/gallery1.png" alt="image-gallery-1">
<img src="images/gallery2.png" alt="image-gallery-2">
<img src="images/gallery3.png" alt="image-gallery-3">
<img src="images/gallery4.png" alt="image-gallery-4">
<img src="images/gallery5.png" alt="image-gallery-5">
</section>
</section>
JavaScript
(function(){
let image-preview = document.getElementById("gallery-preview");
let image-thumbnail = document.getElementById("gallery-thumbnails");
image-thumbnail.addEventListener("click", imageChanger);
function imageChanger()
{
//something here
}
})();
Don't use hyphens in your JavaScript variable names. The dash is for subtraction. You can use dashes in class names and element id's, but not as JavaScript variable names.
Your html needs a class for all your images.
<section id="gallery-thumbnails">
<img class="my-images" src="images/gallery1.png" alt="image-gallery-1">
<img class="my-images" src="images/gallery2.png" alt="image-gallery-2">
<img class="my-images" src="images/gallery3.png" alt="image-gallery-3">
<img class="my-images" src="images/gallery4.png" alt="image-gallery-4">
<img class="my-images" src="images/gallery5.png" alt="image-gallery-5">
</section>
Next, your JavaScript runs asynchronously. You need to understand that. It means that you should not attempt to run your "imageChanger()" function until all the html is loaded. If the html is still loading, some of it might not be present when your function tries to attach the eventListener to it.
By asynchronous, it means JavaScript runs and doesn't wait around for long processes to finish before executing the next line of code. You can do quick things, like add a couple of numbers, but when you are grabbing data from a server and presenting it in html pages, these things take time. You need to be sure you work on them only after they are ready.
To ensure the html is loaded, look into jquery's $(document).ready() {}. You will need to include Jquery with a <script> tag to use it.
$(document).ready() {
let myImages = document.getElementsByClassName("my-image");
// You have more than one image in myImages.
for (i = 0; i < myImages.length; i++) {
myImages.addEventListener("click", imageChanger);
}
}
// Notice this function is **outside** of document.ready.
// You need the function immediately available.
function imageChanger()
{
// "this" is the element you clicked.
this.style.height = 100px;
this.style.width = 100px;
}
(function(){
let imagePreview = document.querySelector("#gallery-preview img");
let imageThumbnail = document.getElementById("gallery-thumbnails");
imageThumbnail.addEventListener("click", imageChanger);
function imageChanger(e) {
imagePreview.src = e.target.src;
}
})();
I am quite new at JQuery (in fact, new to JS too) and I am trying to add a fade in effect to a JS function wich I wrote to change images in a photo gallery when the "thumbnail" of another image is selected. Code is:
//For HTML - the "thumbs" area:
<img id="g1" class="thg" onclick="trocafoto(this.id)" src="fotos/sopa.jpg">
<img id="g2"class="thg" onclick="trocafoto(this.id)" src="fotos/salmao.jpg">//and so on
//The place where pictures are displayed:
<img class="portif" id="alvo" src="fotos/sopa.jpg">
//The JS Function itself:
function trocafoto(id) {
var x = document.getElementById(id).src ;
document.getElementById("alvo").src = x;
}
I'd like to add a JQuery Fade Out effect for the previous image displayed, and the Fade In for the last selected image once the funcion is fired. But I am not finding a way to mix the JQuery Code with the plain JS... How could I call only the JQuery function without need to target it to the same element again?
Thanks in advance for any help.
Try this:
var $alvo = $('#alvo');
$('.thg').on('click', function(){
var clickedImgSrc = $(this).attr('src');
// first hide alvo
$alvo.fadeOut( "slow", function() {
// fadeOut Animation is complete.
// Add the new src to alvo and fadeIn
$(this).attr('src', clickedImgSrc).fadeIn();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="g1" class="thg" src="fotos/sopa.jpg">
<img id="g2" class="thg" src="fotos/salmao.jpg">
<img class="portif" id="alvo" src="fotos/sopa.jpg">
Instead of this
document.getElementById("alvo")
You can reach an element using
$("#alvo")
So in your case
$("#alvo").fadeOut();
would work for example.
If you're using thumbnails than probably you do have higher resolution images too.
That's good for faster page loading! So in that case store the higher quality image path inside a data-* attribute like:
var $alvo = $("#alvo"); // The larger target image
$(".thg").on("click", function(){
// First, make sure the HQ image is loaded from the server
var img = new Image();
$(img).on("load", function(){
// Than assign it to #alvo
$alvo.hide().prop("src", img.src).fadeIn();
});
// getting the path from data attribute of the clicked thumbnail
img.src = this.dataset.hq;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="thg" src="//placehold.it/60x60/cf5" data-hq="//placehold.it/400x200/cf5">
<img class="thg" src="//placehold.it/60x60/f5c" data-hq="//placehold.it/400x200/f5c">
<br>
<img id="alvo" src="//placehold.it/400x200/cf5">
If you don't want the loading image delay than you could preload in a loop all the HQ images, but that defies the purpose of faster page load. A remedy could be adding a loading spinner when a thumbnail is clicked.
I'm new to the site and also to JavaScript. I started writing this little UserScript as a start. Basically what it does is, when you hover your mouse pointer over a thumbnail image, if enlarges that picture to a popup window.
I used Firebug and identified the right code block which contains the image URL.
<div id="profPhotos">
<a class="profPhotoLink" href="photo.php?pid=6054657&uid=1291148517">
<img width="163" height="130" src="http://th0.max.ipstatic.net/thumbs/163x130/0e/e9/604x402_1291148517_6054657.jpg">
</a>
<br>
</div>
And I wrote the below code to retrieve the URL to a variable.
var thumbURL = document.getElementById("profPhotos").getAttribute("src");
But when I run that piece of code in the Firebug console just to check it, it retrieves null.
Am I doing something wrong here? Your kind help would be very much appreciated. :)
You didn't show your hover code, but that is the key. I assume that <div id="profPhotos"> has multiple images and you want to act on the hover of each one?
Also, this can be a pain in plain javascript, and you'll want to use mouseenter versus mouseover, but it's not supported natively in Chrome.
The solution to both these problems is to use jQuery.
Using jQuery, code something like this will get you the image src:
$('#profPhotos .profPhotoLink > img').bind (
"mouseenter mouseleave", myImageHover
);
function myImageHover (zEvent) {
if (zEvent.type == 'mouseenter') {
console.log ('Entering src: ', this.src);
}
else {
console.log ('Leaving src: ', this.src);
}
}
With that code, you will see the src of whichever image logged to the console.
You can see this code in action at jsFiddle.
To get the src of the first image without the mouseover bit (or jQuery), use:
var thumbURL = document.querySelector ('#profPhotos .profPhotoLink > img').src;
profPhotos has no attribute called src, you need to find the img then you can retrieve the source. If you give the image an ID you can then find that and retrieve the src url.
<img id="profPhotos" width="163" height="130" src="http://th0.max.ipstatic.net/thumbs/163x130/0e/e9/604x402_1291148517_6054657.jpg">
Give img tag an id
<img width="163" height="130" src="http://th0.max.ipstatic.net/thumbs/163x130/0e/e9/604x402_1291148517_6054657.jpg" id="imgPhoto"/>
and then call getAttribute for that Id.
var thumbURL = document.getElementById("imgPhoto").getAttribute("src");
If you cannot modify the code, use:
var thumbURL = document.getElementById("profPhotos").getElementsByTagName('img')[0].src;
Access the div, then the only (first) image in it.