Add onmouseover controls - javascript

would like to add a play/stop button to an image onmouseover. I have several images in the same div that are called separately. If Image A is called I would like to have a arrow icon/button appear on the image. And onmouseout, the arrow/icon button to disappear from the image. I do not need this on all my images.
The functionality of the icon/button will be to change Image A to it's loop form and back.
Thanks for any help.
Here's what I have used so far: Not sure this is the most efficient way, but I have the main chart and call other charts as overlays, some are transparent layers some are not. When the main map is displayed, I want to call the buttons that float on top of the map. these will utilize the onmouseover/mouseout. And when clicked I want to change the main map to its loop version.
#chart
{
width: 1000px;
height:700px;
border: solid 1px #d9d9d9;
vertical-align: middle;
position: relative;
z-index: 1;
float: left;
}
<div id="chart">
<img name="mymap" src="http://www.dalta.com/still_image.gif"
width="1000px" height="700px" alt="Map" align="middle" />
<div class="basemap" id="HI_basemap" >
<img src="WEB_HI_BASEMAP.gif" width="1000" height="700"></div>
<div class="basemap" id="HI_etp" >
<img src="WEB_HI_ETP_BASEMAP.gif" width="1000" height="700"></div>
<div class="basemap" id="HI_vor" >
<img src="WEB_VOR_HAWAII.gif" width="1000" height="700"></div>
<div class="basemap" id="HI_route" >
<img src="WEB_ROUTES_HI.gif" width="1000" height="700"></div>
</div>
Tried this instead, but need a way to make infinite loop between 2 images.
intImage = 2;
function swapImage() {
switch (intImage) {
case 1:
IMG1.src = "http://ftpweb.delta.com/weather/WEB0HR.gif"
intImage = 2
return(false);
case 2:
IMG1.src = "http://ftpweb.delta.com/weather/WEB.gif"
intImage = 1
return(false);
}
}
I call this with an onClick but it only lets me do the function 1 time. Any ideas?

Then you can add the id attribute, to the image A. Such as this:
<img src="link/to/file.png" alt="photo" id="a" />
Now the JS would be as:
$('#a').hover(function () {
// do what so ever,
}
$('#a').mouseleave(function () {
// do what so ever,
}
There are many other events in the API. You can use them, and execute the code. However to play/stop you can do this:
$('#a').hover(function () {
$('.audioFile').play();
}

This can be achieved by giving a unique id to each of the images .
Then use getElementById("some id") to get a reference to that image. Then attach the onMouseOver and onMouseOut events to these refernces. This task will become very simple if you give a systematic id to the images like img1,img2 etc since you can use a for loop in this case.

Related

JS: mouseOver function: new state doesn't pick up css from the old state

I'd like to use the mouseOver/mouseOut function in JS to change the colour of an icon.
The icon is white but I'd like it to turn turquoise upon hover over and then back to white when the mouse moves away from the icon.
In my file I have 3 docs:
.html
.css
.js
and 2 images:
skull.png (white icon)
skull2.png (turquoise icon)
Here is my html:
<div id='skull'>
<a href="#" onmouseover="mouseOver()" onmouseout="mouseOut()">
<img class="icon" src="skull.png" alt="skull"/></a>
</div>
Here is my css for the 'icon' class:
.icon {
margin: 0 25px;
height: 40px;
width: 40px;
}
And the js for the function:
function mouseOver() {
document.getElementById("skull").innerHTML = '<img src="skull2.png" />';
}
function mouseOut() {
document.getElementById("skull").innerHTML = '<img src="skull.png" />';
}
I'm having two issues:
The first is that when I hover over the white skull, the skull whilst turning turquoise does not pick up the dimensions set out by the "icon" class. The dimensions are the size of the .png rather. I'd like them the size of skull.png as specified in the css. Not sure how this works?
When you hover off the turquoise skull, the icon does not return to white
Here is a video to show what I mean a little more: https://www.screenmailer.com/v/I5amMjkBaaeLtLU
(Apologies I'm pretty new to programming)
Thanks :)
First of all, you do not have to change the entire inner HTML, and you could go about it by changing only the image src attribute. This way you can get the image by ID only once and not every time that the function is called.
var img = document.getElementById('myImg');
img.onmouseout = function () {
this.src = 'http://www.facetheforce.today/darthvader/200/200';
};
img.onmouseover = function () {
this.src = 'http://www.facetheforce.today/c3po-alt/200/200';
};
<img id="myImg" src="http://www.facetheforce.today/darthvader/200/200"/>
Another way you can go about it is by using CSS hover and background image.
For example:
#bg-image {
width: 200px;
height: 200px;
display: block;
background: url("http://www.facetheforce.today/darthvader/200/200");
}
#bg-image:hover {
background: url("http://www.facetheforce.today/c3po-alt/200/200");
}
<div id="bg-image"></div>
Try this
function mouseOver() {
document.getElementById("skull").innerHTML = '<a href="#" onmouseover="mouseOver()" onmouseout="mouseOut()"><img src="skull2.png" class="icon" alt="skull" />';
}
function mouseOut() {
document.getElementById("skull").innerHTML = '<a href="#" onmouseover="mouseOver()" onmouseout="mouseOut()"><img src="skull.png" class="icon" alt="skull" />';
}
You are not setting the img class as .icon. Also, your areremoving the anchor from your div in the first mouseOver call because you are replacing it's content by <img src="skull2.png" />
This must solve your two problems, but there's a better way to do this.
Add an id to your image, then get in the functions and change only the images's src attribute.

Change multiple images on mouse over , with one function

I have an Exercise to querySelect the image from the HTML and change it on mouseover , I did that correctly like this :
var img = document.querySelector("#image1").addEventListener('mouseover' ,function (){
this.src="images/image1_2.jpg")}
The question is that I have an advanced exercise to change five images in the same way but with " one function "
I did it with five function this way :
const image1 = document.querySelector("#image1")
const image2 = document.querySelector("#image2")
const image3 = document.querySelector("#image3")
const image4 = document.querySelector("#image4")
const image5 = document.querySelector("#image5")
image1.addEventListener('mouseover', function (){
this.src = "images/image1_2.jpg"
})
image2.addEventListener('mouseover' , function (){
this.src= "images/image2_2.jpg"
})
image3.addEventListener('mouseover', function (){
this.src = "images/image3_2.jpg"
})
image4.addEventListener('mouseover', function (){
this.src = "images/image4_2.jpg"
})
image5.addEventListener('mouseover', function (){
this.src = "images/image5_2.jpg"
})
, but I need to do it with one function , any hint on how to do it ?
I hope your img has an initial src. Otherwise you won't be able to mouse over it.
That being said. You will need to use a className instead of an id for each image because they are the same category.
<img src="images/image1_1.jpg" class="token" />
<img src="images/image2_1.jpg" class="token" />
<img ...
Change token to whatever you like.
And then select them by using either document.getElementsByClassName or document.querySelectorAll. They return an HTML collection which is an array-like object.
var images = document.querySelectorAll(".token");
In the snippets below, I use simple divs to illustrate what can be done.
Using forEach loop. you will have to convert the collection to an array in order to use forEach
var imgs = [ ...document.querySelectorAll(".img") ];
imgs.forEach((img, i) => {
img.addEventListener('mouseover', function () {
this.textContent = "images/image" + (i + 1) + "_2.jpg";
});
});
div {
width: 200px;
height: 30px;
float: left;
margin: 5px 1em;
font-weight: bold;
color: white;
text-shadow: 1px 1px 0 black;
}
<div class="img" style="background: #234;"></div>
<div class="img" style="background: #7fb;"></div>
<div class="img" style="background: #ace;"></div>
<div class="img" style="background: #d8f;"></div>
<div class="img" style="background: #e6a;"></div>
Using a simple for loop. no need for convertion
var imgs = document.querySelectorAll(".img");
for (let i = 0; i < imgs.length; i++)
imgs[i].addEventListener('mouseover', function () {
this.textContent = "images/image" + (i + 1) + "_2.jpg";
});
div {
width: 200px;
height: 30px;
float: left;
margin: 5px 1em;
font-weight: bold;
color: white;
text-shadow: 1px 1px 0 black;
}
<div class="img" style="background: #234;"></div>
<div class="img" style="background: #7fb;"></div>
<div class="img" style="background: #ace;"></div>
<div class="img" style="background: #d8f;"></div>
<div class="img" style="background: #e6a;"></div>
Maybe make the event listener 'listen' on the body element, then check which element was hovered whith an if statement. I think it can be done whithout 'if' too. You will have to use 'this'.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Don't ask us to do your exercice, but ask for a hint so you can do it by yourself and learn.
You are close to the solution. What you want is, when you hover any of the images, you want to change all the src. So your code must be something like :
When I hover any of my images (use document.getElementsByClassName), I've got a function which instead of changing the source of the current image changes the source of the five images (so you'll have a line by image to change each src).
Your question is unclear if you want to change ALL images with one hover or one-by-one.
If you want to change all images in same time, your function should look something like this.
function changeall{
document.getElementById("image1").src="....";
document.getElementById("image2").src="....";
document.getElementById("image3").src="....";
document.getElementById("image4").src="....";
document.getElementById("image5").src="....";
}
If you want to change it one by one it will require your to modify your html code also.I don't want to finish your exercise therefore I will only write you main points that you need to look after
Make your images have same class
Add two functions onmouseover and one onmouseout
One function should change custom attribute so that you know which image was hovered on
example:
<img .... onmouseover="changeimg();function(){document.getElementById("id-of-that-img").customattribute ="1";}" onmouseout="document.getElementById("id-of-that-img").customattribute ="0";}">
I know that it is kinda messy but I didn't want to create separate named functions for this.
When customattribute is at 0 you know that it is not being hovered on, and when its 1 you know that it is.
Make a loop for checking each element of that class if it has customattribute === 1.
I would personally use a variable to counter for my images.
something like this:
var counter = 0;
var x =setInterval(function(){
if(document.getElementsByClassName('class')[counter].customattribute===1){
//what_to_do_if_img_is_being_hovered_on}
clearInterval(x);
//stops the loop
else{
counter++;}},1);
I haven't tried the code out and it probably has a flaw but it is there just to give you a hint about how you can solve your problem.

i have to click twice, why? (JavaScript onclick event handler)

i am new to JavaScript and web development and it is the first time i see this kind of bugs. it is a very basic example, i have two divs- left and right- the left one has five images and the right one is empty , i have also two buttons copy and delete, each has an onclick event handler. the Copy button copies the entire left node (div) and appends it to the right div , the delete button should delete the last image in the right div and it does, the thing is i have to click twice on Delete button to delete one image so i have to click 10 times to delete the entire set. why this happens? what should i do to make the Delete button deletes an image by just clicking once ?
this is my entire code , tested on Microsoft Edge and Google chrome and i got the same result.
var theLeftSide = document.getElementById("leftSide");
var theRightSide = document.getElementById("rightSide");
function Copy() {
copy = theLeftSide.cloneNode(true);
theRightSide.appendChild(copy);
}
function Delete() {
copy.removeChild(copy.lastChild);
}
div {
position: absolute;
width: 670px;
height: 520px;
background: red
}
#rightSide {
position: absolute;
left: 670px;
border-left: 1px solid black;
background: black
}
<input type="button" value="Copy" onclick="Copy()">
<input type="button" value="delete" id="btn" onclick="Delete()">
<div id="leftSide" style="width:400px">
<img src="smile.png" />
<img src="smile.png" />
<img src="smile.png" />
<img src="smile.png" />
<img src="smile.png" />
</div>
<div id="rightSide">
</div>
Most browsers instert by default an empty text node between each element of your page, your code is deleting one empty node for every img, that's why it seems to work half of the times.
Try this:
function Delete(){
var imgs = document.querySelectorAll('.rightSide img');
copy.removeChild(imgs[imgs.length-1]);
}
You're removing text nodes as well as elements. What you really want is copy.removeChild(copy.lastElementChild);

Can each new click produce a new image?

I know how to make an image appear using onclick or onMouseOver but how can I make each click produce the appropriate image not just in the same place but, for example, in a row, next to it's previous apperance? My idea is this: I click on reference1 and a picture1 shows up. Then I click on reference2 and a picture2 shows up next to the picture1 already displayed. Now I click on reference1 again, and I want to see pictures 1,2,1 in a row. How can I do that? My ideal would be to see the row rolling when filled, and a delete button deleting the last image in that row, even making the pictures jump out being called from the text field, but I can search for these myself. My greatest concern for now is new click=new image. Thank you.
Assuming this is relatively simplistic- you could keep track of the current position in a list of images, afterwards create a function that deals with the current image then increments this position. Have the onClick event call this function, and there you are.
An example of this in action, using JQuery, can be viewed here:
http://jsfiddle.net/8Q4LQ/
Here's an example.
<html>
<head>
<style>
.refimg { width: 100px; height: 100px; }
.choices a { margin-right: 2ex; }
.choices img { display: none; }
#target { display:block; width: 500px; overflow-x: scroll; border: 1px solid black; }
</style>
</head>
<body>
Choices:
<div class="choices">
ref1
ref2
<image id="image1" src="image1.gif" class="refimg" />
<image id="image2" src="image2.gif" class="refimg" />
</div>
<br />
Selections: <input type="button" value="Delete" onclick="delImage()" />
<nobr id="target">
</nobr>
<script>
function putImage(src) {
var a = src.cloneNode(true);
a.id = ''; //clear id to prevent duplicate id
target.appendChild(a);
a.scrollIntoView(true);
return false;
}
function delImage() {
var a=target.children;
if (a.length>0) target.removeChild(a[a.length-1]);
}
target.style.height=((target.offsetHeight-target.clientHeight)+100)+'px'; //extend height for scroll bar
</script>
</body>
</html>

jQuery fade to new image

How can I fade one image into another with jquery? As far as I can tell you would use fadeOut, change the source with attr() and then fadeIn again. But this doesn't seem to work in order. I don't want to use a plugin because I expect to add quite a few alterations.
Thanks.
In the simplest case, you'll need to use a callback on the call to fadeOut().
Assuming an image tag already on the page:
<img id="image" src="http://sstatic.net/so/img/logo.png" />
You pass a function as the callback argument to fadeOut() that resets the src attribute and then fades back using fadeIn():
$("#image").fadeOut(function() {
$(this).load(function() { $(this).fadeIn(); });
$(this).attr("src", "http://sstatic.net/su/img/logo.png");
});
For animations in jQuery, callbacks are executed after the animation completes. This gives you the ability to chain animations sequentially. Note the call to load(). This makes sure the image is loaded before fading back in (Thanks to Y. Shoham).
Here's a working example
$("#main_image").fadeOut("slow",function(){
$("#main_image").load(function () { //avoiding blinking, wait until loaded
$("#main_image").fadeIn();
});
$("#main_image").attr("src","...");
});
Well, you can place the next image behind the current one, and fadeOut the current one so that it looks like as though it is fading into the next image.
When fading is done, you swap back the images. So roughly:
<style type="text/css">
.swappers{
position:absolute;
width:500px;
height:500px;
}
#currentimg{
z-index:999;
}
</style>
<div>
<img src="" alt="" id="currentimg" class="swappers">
<img src="" alt="" id="nextimg" class="swappers">
</div>
<script type="text/javascript">
function swap(newimg){
$('#nextimg').attr('src',newimg);
$('#currentimg').fadeOut(
'normal',
function(){
$(this).attr('src', $('#nextimg').attr('src')).fadeIn();
}
);
}
</script>
Are you sure you're using the callback you pass into fadeOut to change the source attr and then calling fadeIn? You can't call fadeOut, attr() and fadeIn sequentially. You must wait for fadeOut to complete...
Old question but I thought I'd throw in an answer. I use this for the large header image on a homepage. Works well by manipulating the z-index for the current and next images, shows the next image right under the current one, then fades the current one out.
CSS:
#jumbo-image-wrapper
{
width: 100%;
height: 650px;
position: relative;
}
.jumbo-image
{
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
HTML:
<div id="jumbo-image-wrapper">
<div class="jumbo-image" style="background-image: url('img/your-image.jpg');">
</div>
<div class="jumbo-image" style="background-image: url('img/your-image-2'); display: none;">
</div>
</div>
Javascript (jQuery):
function jumboScroll()
{
var num_images = $("#jumbo-image-wrapper").children(".jumbo-image").length;
var next_index = jumbo_index+1;
if (next_index == num_images)
{
next_index = 0;
}
$("#jumbo-image-wrapper").children(".jumbo-image").eq(jumbo_index).css("z-index", "10");
$("#jumbo-image-wrapper").children(".jumbo-image").eq(next_index).css("z-index", "9");
$("#jumbo-image-wrapper").children(".jumbo-image").eq(next_index).show();
$("#jumbo-image-wrapper").children(".jumbo-image").eq(jumbo_index).fadeOut("slow");
jumbo_index = next_index;
setTimeout(function(){
jumboScroll();
}, 7000);
}
It will work no matter how many "slides" with class .jumbo-image are in the #jumbo-image-wrapper div.
For those who want the image to scale according to width percentage (which scale according to your browser width), obviously you don't want to set height and width in PIXEL in CSS.
This is not the best way, but I don't want to use any of the JS plugin.
So what can you do is:
Create one same size transparent PNG and put an ID to it as
second-banner
Name your original image as first-banner
Put both of them under a DIV
Here is the CSS structure for your reference:
.design-banner {
position: relative;
width: 100%;
#first-banner {
position: absolute;
width: 100%;
}
#second-banner {
position: relative;
width: 100%;
}
}
Then, you can safely fade out your original banner without the content which placed after your image moving and blinking up and down

Categories

Resources