javascript to change image source when hover over button - javascript

Javascript noob here. I've looked for related questions but all the results won't work for me or I don't really understand parts of them. So I might just have done a silly mistake here.
What I'm trying to do is a script that when I hover over a button, changes the source of an image.
HTML:
<button onmouseover="changeImg()" class="about" href="#">ABOUT</button>
<img class="image2" src="images/image2.png">
Javascript:
<script>
function changeImg()
{
var image = document.getElementsByClassName("image2");
image.src = "images/image1.png"
}
</script>
Is there maybe an easier way to do it? I prefer using only html css and javascript.
Thanks for the help!

You’re using getElementsByClassName which will return an array of all the elements with that class. Either use document.getElementByClassName or document.querySelector(“element”)
function changeImg() {
var image = document.getElementByClassName("image2");
image.src = "images/image1.png"
}
Another solution is to use an event listener with the e variable:
document.querySelector(“.about”).addEventListener(“mouseover”, function (e) {
e.target.src = “newSource”
})
The e.target is the image element

Related

Javascript: Using onmouseover and onmouseout functions on more than one image

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

Javascript, after eventhandler back to default (DOM)

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

Javascript function not being run from click - what am I doing wrong?

I am currently making some accessibility options which make the font size increase or decrease on a page. Following EndangeredMassa's for calling JS from a link it appears not to work!
My current code (which is dummy code with the right IDs which will be used in my actual site), does not even run a Javascript alert, and since I'm not one for Javascript, if anyone could let me know what I'm doing wrong.
HTML
<p id="html">Nice to meet you!</p>
<a id="incFontS" href="#">Increase Text</a>
JavaScript
var incFont = document.getElementById("incFontS");
incFont.onClick = function () {
window.alert("it ran!");
}
As you can see from my jsfiddle, the code does not work at all, and I haven't even gotten to the part where I start changin the font sizes (geh!).
Any help is greatly appreciated!
Case matters in JavaScript. The correct property name is onclick (with a lowercase 'c'). Try this:
var incFont = document.getElementById("incFontS");
incFont.onclick = function () {
window.alert("it ran!");
}
Demonstration
Also, be sure to read addEventListener vs onclick for a discussion about different techniques for binding event listeners.
DEMO
var incFont = document.querySelector("#incFontS");
incFont.addEventListener('click', function () {
window.alert("it ran!");
return false;
});
The function name is onclick not onClick
i.e.
var incFont = document.getElementById("incFontS");
incFont.onclick = function () {
window.alert("it ran!");
}
works for me.
Try this way to do increase your font size
HTML CODE
<p id="html">Nice to meet you!</p>
<a id="incFontS" href="#" onclick="myFunction()">Increase Text</a>
Java Script Code
<script>
function myFunction() {
document.getElementById("html").style.fontSize="xx-large";
}
</script>

using onmouseover to change text hyperlink into an image hyperlink?

Please bear with me I am brand new to learning javascript (self taught)! I am usually one to find answers on my own from just web browsing but so far I haven't found any resources explaining how to accomplish the following:
So, basically all I want to do is change this (HTML):
SPEAKERS
to an image by using javascript.
The image is kept in the same folder as the html and the js.
Here is as far as I know to go with the javascript:
function showImage()
{
picture = new Image(100,100);
picture.src = "icon2.png";
document.getElementById("speakers").innerHTML = picture.src;
}
function goBack()
{
document.getElementById("speakers").innerHTML="SPEAKERS";
}
For clarity, all I would like to do is change the text ("SPEAKERS") to an image using 'onmouseover' while using the same hyperlink in the process.
It seems like a very simple problem but I don't know enough to determine if what I want to do is even possible. If it's not possible that's fine, I would just like to know either way ;P. Thanks ahead of time!
If you're ok with using jquery, you could use .html() and .hover()
http://jsfiddle.net/u8fsU/
Try something like this to get you started (not a complete nor tested solution):
var showImage = function(){
var picture = document.createElement("img");
picture.src = "icon2.png";
picture.href = "link.html";
var speakers = document.getElementById("speakers");
speakers.parentNode.replaceChild(speakers, picture);
}
Please see https://developer.mozilla.org/en-US/docs/Gecko_DOM_Reference for a good reference to some of the available DOM properties and methods.

Can the source of an image be changed upon rollover using JavaScript?

I have a question on rollover effects using JavaScript.
I have read that image sprites (image with another image on its side) can be used with help of CSS offsetting to achieve basic rollover when onmouseover is handled using JS. Have also read about the possibility of changing classes itself using JS (className) to achieve the above effect.
My question is, can I modify the image src itself using JavaScript, to achieve the rollover effect?
A code like this, maybe -
document.getElementByID("button1").onmouseover = rolloverFunction;
function rolloverFunction(){
this.src = "button1-image2.png";
}
I typed something like this to see if the src of the image can be modified upon rollover, but it is not working. Could you please let me know where I am going wrong?
You need the mouseover and mouseout events. mouseover is triggered when hovering in the image, mouseout on leaving the image. Using plain ol' JS would yield:
<img src="default.png" id="image" alt="">
<script>
var image = document.getElementById("image");
image.onmouseover = function () {
this.src = "rollover.png";
};
image.onmouseout = function () {
this.src = "default.png";
};
</script>
Or using a common function to avoid duplicating the URL:
function rollover_effect(img_elm, rollover_src) {
var default_src = img_elm.src;
img_elm.onmouseover = function () {
img_elm.src = rollover_src;
};
img_elm.onmouseout = function () {
img_elm.src = default_src;
};
}
rollover_effect(document.getElementByID("image"), "rollover.png");

Categories