javascript image rollover inside div - javascript

i have a single div 100px X 300px. What's the easiest way in JavaScript so when I hover over the div i show an image and then when i leave the div the image disappears.
for starters i thought the following would get me started but i can't seem to remove the image properly
<script type="text/javascript">
function MouseOver_Event(elementId) {
var imgToCreate = document.createElement('img');
imgToCreate.setAttribute('id', 'imgHandle');
imgToCreate.setAttribute('src', elementId + '.png');
imgToCreate.setAttribute('onmouseout', 'MouseOut_Event('+elementId+')');
var targetDiv = document.getElementById(elementId);
targetDiv.appendChild(imgToCreate);
targetDiv.removeAttribute('onmouseover', 'MouseOver_Event');
}
function MouseOut_Event(elementId) {
var imgToRemove = document.getElementById('imgHandle');
var targetDiv = imgToRemove.parentNode();
if (imgToRemove != null)
targetDiv.removeChild(imgToRemove);
targetDiv.setAttribute('onmouseover', 'MouseOut_Event(' + elementId + ')');
}
</script>
</head>
<body>
<div id="div1" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div2" onmouseover="MouseOver_Event(this.id)"></div>
<div id="div3" onmouseover="MouseOver_Event(this.id)"><img src="Div3.png" alt="test" onmouseout="MouseOut_Event(parentNode's id or something)" /></div>
</body>

You're attaching your MouseOut_Event to onmouseover instead of onmouseout. But you probably don't need to be messing with dynamic event creation anyway; just add onmouseout="MouseOut_Event(this.id)" to the three divs and that should do it.

Why don't you use CSS instead ?
For example:
#div1{background:none;}
#div1:hover{background:url('src/div1.png') no-repeat;}

Related

How to switch 4 images using a button

<html>
<head>
<title>How To Insert an Image</title>
<script>
function changeImage(){
var img = document.getElementById('image');
image.src='image4.jpg';
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
I am quite new to Javascript so please dont be too harsh. Basically im trying to switch from one picture to another using a button. So far with this code i have only managed to do 2 images but when i try to add a 3rd or 4th the first image messess up. I was hoping if someone could help me fix this problem.
Here's simplest approach the I used before, for two images. Easily extended to accomodate three, four, or more alternate images.
<div id="image1">
<img ... >
<button ...>
</div>
<div id="image2" style="display: none">
<img ... >
<button ...>
</div>
That is, put the first image, and a button, inside a "< div >" element, and a second image, and a button inside a second "< div >" element that's initially hidden.
Then, each button's javascript simply needs to set its own div's CSS style to "display: none", and remove this style from the other div element, effectively hiding one image, and displaying the other one.
This approach also makes it possible to update the button's text or label, accordingly. If both buttons have the same label, the only apparent result is the image change.
Try this script block instead:
<script>
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg']
function changeImage() {
var img = document.getElementById( 'image' )
var url = images.shift() // remove first url from list
image.src = url // use it
images.push( url ) // append url to the end of the list
}
</script>
What you could do is declare an array which contains all your image urls:
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
Then when clicking the button, you remove the first image url from the the array by using shift and assign that to variable imageUrl.
Then you set that imageUrl to the src attribute of the image element on your page.
Then you add that imageUrl at the end of the array using push.
This will rotate the images in the imageUrls array on every click.
<html>
<head>
<title>How To Insert an Image</title>
<script>
var imageUrls = ["image2.jpg", "image3.jpg", "image4.jpg", "image1.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
</script>
</head>
<body>
<img id="image" src="image1.jpg" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
You were very close! You just made mistake to assign a value to image.src instead of img.src. have a look at the code below :)
Using clicks:
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}
</script>
</head>
<body>
<img id="image" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" height="100px" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>
</html>
Automatic image slider
<html>
<head>
<title>How To Insert an Image</title>
<script>
i = 1; /*Default value, only executed when the page is loaded (default is the first image, so when i + 1 the second image is displayed on first click.)*/
setInterval(function changeImage(){
var img = document.getElementById('image');
i = i + 1; /*next image*/
if(i == 5) /* if end is reached, reset to first image*/
{
i = 1;
}
img.src='image' + i + '.jpg'; /*number to text in variable, so image + 'number of the image (i)' + extension(.jpg in this case)*/
}, 5000)
</script>
</head>
<body>
<img id="image" src="image1.jpg" height="100px" />
</body>
</html>

Appending the elements within div using appendchild attribute

I have a div as :
<div id="div1" width="100px" height="100px">
</div>
Now within this div I want to place 20 elements, but dynamically it can grow upto 50 elements(images) also.
I am using the following code to append these elements in a div,
var i = document.createElement("img");
var d= document.getElementById("div1");
d.appendchild(i);
Now, the issue is ,as the number of elements increase the elements are going out of div ,and if I use the max-width and max-height on images, the result doesnt change:
i.setAttribute('max-width', '100%');
i.setAttribute('max-height', '100%');
Is there anything which I am missing?
Edit:
The images need to shrink as the div size is fixed
If the width is fixed and the height is dynamic. The image will shrink and they will get stacked. Check my fiddle here
img {
width:100%;
display:inline-block;
}
<div style="width:100px;border: 1px solid black;">
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
<img src="http://www.brightlinkprep.com/wp-content/uploads/2014/04/sample.jpg" />
</div>
Cant think of a nice way to do it with percentages,
var imags = document.getElementsByTagName('img');
var count = imags.length;
for (var index= 0,l= count;index<l;index++){
imags[index].setAttribute('height', (100/count)+'%');;
}
its not pretty but should work.
i smushed something together from all the answers that fits your needs (if i understand you correctly)
https://jsfiddle.net/b30d88g6/3/
the div has fixed width/height and the images wont get out of the div
function add_img() {
var i = document.createElement("img");
i.src= "https://jsfiddle.net/img/logo.png";
var d= document.getElementById("div1");
d.appendChild(i);
var imags = document.getElementsByTagName('img');
var count = imags.length;
for (var index=0, l=count;index<l;index++){
imags[index].setAttribute('height', (100/count)+'%');;
}
}

Assign img' src dynamically

The page will display an image's url text correctly. But I am not sure how to assign the message to the img 's src to display the image.
<DIV class="msgStyle1" id="message">Waiting for image</DIV>
<div class="imgStyle1" id="message">
<img src=whatneedtogohere /></div>
function displayText(text) {
console.log(text);
document.getElementById("message").innerHTML=text;
window.castReceiverManager.setApplicationState(text);
};
Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:
<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
<img src="" id="image" />
</div>
JS:
document.getElementById('image').src = 'http://yourImagePathHere';
See it work here: http://jsfiddle.net/N3rCm/
First off, you shouldn't have multiple Id's on the page, it'll mess with your JS.
Next I would give your image a class if you can
//jquery example of what you would do
var imgSrc = 'http://wherever/youre/getting/this/from';
$('.myimageclass').attr('src', imgSrc);
//non jquery
var myImg = document.getElementsByClassName('myimageclass')[0]; //assuming it's the first one
//or if you can uniquely identify it
var myImg = document.getElementById('imgId');
myImg.src = imgSrc;

change image SRC and Style

Hi I want to rewrite an image Src and Style element.
The image tag has an element called "data-orig-file" wich has the url that I want to write to the src element.
I came up with this but I'm not good at javascript:
function changeImageSrc(img) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
Now Secondly I want to grab the "Style" element with it's values from the grandparent div of the image and write that style to the image instead of the original style.
Finally I want to do these two things on all images inside a container div on a page when it is loaded (I suppose).
Any help is greatly apreciated!!
Thanks
update:
what I came up with so far is this:
function ChangeImageSrc() {
var image=document.getElementById("img");
var div=document.getElementById("LastPost");;
for each (image in div) {
var newurl= document.getElementById("img").getAttribute('data-orig-file');
var oldurl= document.getElementById("img").src;
document.getElementById("img").src = img.src.replace(oldurl, newurl);
}
}
window.onload = function()
{
ChangeImageSrc();
};
I also tried it with an "onload" event on the body element like this (instead of the wondow.onload part):
onload="javascript:ChangeImageSrc()
Both don't work this far :(
Ok AffluentOwl, here's the HTML:
<div class="gallery-group images-1" style="width: 677px; height: 507px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<a href="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg" class="zoom">
<img data-attachment-id="5786" data-orig-file="http://www.mydomain.com/wp-content/uploads/..../../image.jpg" data-orig-size="1333,1000" data-medium-file="http://www.mydomain.com/wp-content/uploads/..../../image-300x225.jpg" data-large-file="http://www.mydomain.com/wp-content/uploads/..../../image-1024x768.jpg" src="http://i0.wp.com/www.mydomain.com/wp-content/uploads/..../../image.jpg?resize=1191%2C893" align="left" title="shelter-childrens-farm" data-recalc-dims="1" style="width: 73px; height: 9px;">
</a>
</div>
</div>
As you can see there is a CDN prefix to the url that I'm trying to loose (for good reasons, it's opposed to me by wordpress and doesn't work for me).
The second thing is about the style of the image tag, that's somehow set to the wrong dimensions so I want to grab the right size from the first div (top of code).
Here's how you replace an images' src attribute with a url stored in an attribute on the image called data-orig-file when the page loads.
<html>
<script>
function ChangeImageSrc() {
var div = document.getElementsByClassName("gallery-group images-1")[0];
var images = div.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("src", images[i].getAttribute("data-orig-file"));
images[i].setAttribute("style", div.getAttribute("style"));
}
}
window.onload = ChangeImageSrc;
</script>
<div class="gallery-group images-1" style="width: 500px; height: 500px;">
<div class="tiled-gallery-item tiled-gallery-item-large">
<img src="a.jpg" data-orig-file="b.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="c.png" data-orig-file="d.jpg" id="image_id" style="width: 100px; height: 100px">
<img src="e.png" data-orig-file="f.png" id="image_id" style="width: 100px; height: 100px">
</div>
</div>
</html>
It would probably be helpful for you to look into the element selection functions in Javascript.
getElementById
getElementsByClassName
getElementsByTagName
querySelector
You may even like to use jQuery which makes selecting elements much easier. In jQuery you could replace the <script> code with the following for the same result as above:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function() {
var div = $(".gallery-group.images-1");
var images = div.find("img");
images.each(function() {
$(this).attr("src", $(this).attr("data-orig-file"));
$(this).attr("style", div.attr("style"));
});
});
</script>

Label being treated as a div

I have a div containing a label and 4 divs. I want some css and jQuery to affect the 4 child divs, but not the label, and so I wrote the following:
HTML:
<div class="score row-fluid">
<label class="span8">Text...</label>
<div class="span1"><img></div>
<div class="span1"><img></div>
<div class="span1"><img></div>
<div class="span1"><img></div>
</div>
CSS
.score > div {
cursor:pointer;
}
jQuery
$('> div', '.score').on('mouseenter', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
var point = $img.attr('src').lastIndexOf('.');
var src = $img.attr('src').substring(0,point);
var newSrc = src + "-hover" + $img.attr('src').substring(point);
$img.attr('src', newSrc);
}
})
.on('mouseleave', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
var point = $img.attr('src').lastIndexOf('.');
var point2 = $img.attr('src').lastIndexOf('-hover');
var src = $img.attr('src').substring(0,point2);
var newSrc = src + $img.attr('src').substring(point);
$img.attr('src', newSrc);
}
});
However the label has a pointer cursor, and it fires the mouseenter/leave JavaScript.
I've created a fiddle here, and interestingly it's not firing the JavaScript on the fiddle, but it is still being affected by the css.
Does anyone know why this label is being treated as if it's a div?
Bootstrap is giving label the pointer, and your mouse events are being called on .score as well as > div. When you hover over the label, you are also hovering over .score
EDIT: I changed the logging on your JS fiddle, here http://jsfiddle.net/sEa5W/1/
The mouse enter isn;t getting fired from the label, but the mouse exit is being called when you hover over to the mouse label from one of the DIVs because you are exiting the DIV.
perhaps it is an idea (if you use html5) to use <img data-large="path-to-large-image" and use that in your jQuery selection.
<div class="score row-fluid">
<label class="span8">Text...</label>
<div class="span1"><img src="thumbnail1.jpg" data-large="fullsize1.jpg" alt="img1" /></div>
<div class="span1"><img src="thumbnail2.jpg" data-large="fullsize2.jpg" alt="img2"></div>
<div class="span1"><img src="thumbnail3.jpg" data-large="fullsize3.jpg" alt="img3"></div>
<div class="span1"><img src="thumbnail4.jpg" data-large="fullsize4.jpg" alt="img4"></div>
</div>
and the jQuery:
$('div.score>div.span1').on('mouseenter', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
$img.attr('src', $img.attr('data-large'));
}
})
.on('mouseleave', function() {
if($(this).not('.score-selected')) {
var $img = $(this).children('img');
$img.attr('src', $img.attr('data-large'));
}
});
edit lol, just noticed I used large twice, but this can also be done with small or something. just data-anything. It was just a way to show you that you do not have to manipulate strings, but that you can use html5 data attributes.

Categories

Resources