Change Image OnClick & OnMouseover - javascript

I am a complete nub with JS, but I fiddle with it occasionally when necessary. I am writing a function that changes two images on a page (before & after gallery images) when a sliding image is click / selected from a marquee below them. I have that working. The problem is that I also need to change the AFTER image when the BEFORE image is moused over, and I dont seem to be able to pass that variable to the function correctly - here is what I have:
<script>
function changeImage(imgName)
{
var img = imgName;
img += 'a.jpg';
var img1 = imgName;
img1 += 'b.jpg';
image = document.getElementById('imgDisp');
image.src = img;
image = document.getElementById('imgDisp1');
image.src = img1;
}
function swap1(image)
{
var img = 'newgallery/';
img += image;
img += 'b.jpg';
image = document.getElementById('imgDisp');
image.src = img;
}
function swap2(image)
{
var img = 'newgallery/';
img += image;
img += 'a.jpg';
image = document.getElementById('imgDisp');
image.src = img;
}
</script>
<table border=0 width=85%>
<tr>
<td align=center valign=top>
<img id="imgDisp1" src=newgallery/1b.jpg height=80
onmouseover="swap1(img)"
onmouseout="swap2(img)"
>
<p class=content>BEFORE</b></p></td>
<td width=35></td>
<td align=center><img id="imgDisp" src=newgallery/1a.jpg width=550></td>
</tr>
</table>
<marquee behavior="scroll" direction="left" scrollamount="3" onMouseOver="this.stop();" onMouseOut="this.start();">
<?php
$imagenum = '1';
$imageset = 'a.jpg';
$imagesetalt = 'b.jpg';
while($imagenum < 37){
$imagename = "$imagenum$imageset";
$imagethumb = "$imagenum$imagesetalt";
if($imagenum == '13'){
}else{
echo"
<img src=\"newgallery/$imagename\" height=\"120\" border=0 onclick=\"changeImage('newgallery/$imagenum')\">
<img src=images/spacer.gif width=25 height=1>";
}
$imagenum++;
}
?>
I can change the images on click in the marquee calling the changeImage function because I can pass the assigned image name variable to the function. I cannot seem to figure out how to pass the BEFORE thumbnail image name variable to the mouseover functions (swap1) & (swap2) respectively. This may just be a simple syntax solution - but again I dont know JS well enough to figure it out - any assistance would be appreciated.

Honestly, your code is a little overcomplicated. You can simplify this by taking advantage of the data attribute of HTML elements.
Lets say you have a container defined as
<div id = 'img_container' class = 'some_class'>
<img id = 'image' class = 'some_image_class' src = '/path/to/default/image.jpg'
data-alt = '/path/to/hover/image.jpg' />
</div>
You can define a function to retrieve the path stored in the data attribute and swap the data and source values via
function swap(image){
//temporary variable to hold the alternate image path
var newImage = image.data("alt");
//store the image src attribute in the `data-alt` attribute
image.data("alt", image.attr("src");
//replace the image src attribute with the new image path
image.attr("src", newImage);
}
Now, you can apply events to the image via
$("#image").on("mouseover", function(e){
swap($(e.currentTarget));
})
.on("mouseout", function(e){
swap($(e.currentTarget));
});
This will allow you to replace the onmouseover and onmouseout events in your HTML.

Related

Change Image Source from Div with onmouseover

Is it possible to change the image source from the containing div? The images are dynamic and pulled from the database.
v = $"<div onmouseover=\"document.navIcon.src='/Images/White/{reader[2]}';\"
onmouseout=\"document.navIcon.src='/Images/{reader[2]}';\">
<img name=\"navIcon\" src=\"Images/{reader[2]}\"><br>{reader[1]}</div>";
That was my thoughts on how to do it but it doesn't appear to work as expected. I was able to get it to work when I put the onmouseover portion in the < img > however, I want it to change anywhere in the div, like over the reader[1] text, not just directly over the image.
Thoughts?
I just grabbed some images off google images. You can use this to refer to the current element.
<img
src='https://osu.ppy.sh/forum/images/smilies/50.gif'
onmouseover='this.src="http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png"'
onmouseout='this.src="https://osu.ppy.sh/forum/images/smilies/50.gif"'
/>
Edit..
This will change the image when you hover on anything with a "hoverme" class name.
(function() {
var img1 = "https://osu.ppy.sh/forum/images/smilies/50.gif";
var img2 = "http://4.bp.blogspot.com/-YrmTHhfMtFU/VJNbpDMHzgI/AAAAAAAAH8c/g3dJ1Q-QTrc/s1600/smile.png";
var myimg = document.getElementById('myimg');
myimg.src = img1;
var hoverables = document.getElementsByClassName('hoverme');
for (var i = hoverables.length; i--;) {
hoverables[i].addEventListener("mouseover", hoverMe, false);
hoverables[i].addEventListener("mouseout", unhoverMe, false);
}
function hoverMe() {
myimg.src = img2;
}
function unhoverMe() {
myimg.src = img1;
}
})();
<img class='hoverme' id='myimg' />
<p class='hoverme'>poooooooop</p>
<div class='hoverme'>This si a diiiiivvvvv</div>
The best way to accomplish that is to use CSS.
HTML
<img id="NavIcon">
CSS
#Navicon {
background-image: url(image1.jpg);
}
#NavIcon:hover {
background-image: url(image2.jpg);
}

Add Links to Images in a Script

This script replaces the background of the DIV 'middle' with the images listed in the array. Currently the script works perfect but I want to be able to assign a link to each image, tried just replacing with but then the image doesn't show up nor does the link work.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg');
var nextimage=0;
doSlideshow();
function doSlideshow(){
if(nextimage>=images.length){nextimage=0;}
$('.middle')
.css('background-image','url("'+images[nextimage++]+'")')
.fadeIn(500,function(){
setTimeout(doSlideshow,5000);
});
}
</script>
What I'm looking for is something like this.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg'); To: var images=new Array('<img src="/images/home/imgone.jpg"', '<img src="/images/home/imgtwo.jpg"', '<img src="/images/home/imgthree.jpg"', '<img src="/images/home/imgfour.jpg"', '<img src="/images/home/imgfive.jpg"');
</script>
Although this does not fully answer your question, maybe you can get some ideas from DOM functions.
Example
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.body.appendChild(image);
</script>
This appends an image to the body. If you would like to add it to a specific ID, you could do the following (assuming your div id is "destination").
Example
<!DOCTYPE html>
<html>
<body>
<div id="destination">
<!-- Destination Div -->
</div>
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.getElementById("destination").appendChild(image);
</script>
</body>
</html>
Good luck!

All purpose image swap function

Ok, I am new to JavaScript so please keep that in mind when you answer. What I am looking for is a function that I can use that will enable me to click an image, then click another image and swap their positions on the page. For example I have a 3x4 table with 12 separate images, I click on 'image1' and then click 'image3' and the two swap. The only solutions I have found deal with swapping an image with a specified image, this is not what I need. Hope this makes sense.
Any suggestions and solutions are welcomed to help me learn! Thank you!
Also, I would like this to be 100% JavaScript and not jQuery.
HTML:
<table>
<tr>
<th id="pos1"> <img src="pic_01.gif" id="pic1" onclick="imageSwap()" alt="" border= height=100 width=100></img> </th>
<td id="pos2"> <img src="pic_02.gif" id="pic2" alt="" border= height=100 width=100> </img></td>
<td id="pos3"> <img src="pic_03.gif" alt="" border= height=100 width=100></img></td>
</tr>
Attempted JS:
imgArray[0] = new Image();
imgArray[0].src = 'pic_01.gif';
imgArray[1] = new Image();
imgArray[1].src = 'pic_02.gif';
imgArray[2] = new Image();
imgArray[2].src = 'pic_03.gif';
etc etc...
var a
var b
function imageSwap(){
getElementById.src = a
Not sure at all what to do for the swap itself
So I was bored and felt like being nice, so here's an example of image swapping, even though you made no attempt. Try to avoid being distracted by the cute kittens.
The part of the code that matters is the script:
var position = null,
target = null;
$("img").click(function(){
if ($(this).attr("class") == "border"){
$(this).toggleClass("border");
target = null;
position = null;
return false;
}
else{
$(this).toggleClass("border");
if (position == null){
position = $(this).attr("src");
$(this).toggleClass("position");
}
else{
target = $(this).attr("src");
$(this).attr("src", position);
$(".position").attr("src", target)
.toggleClass("position");
$(".border").toggleClass("border");
position = null;
target = null;
}
}
})
The <html> is just a set of images and the CSS just adds some margins and the border for the image you click. In short, the code checks whether the image has been selected. If it already has a selection border and you click it again, it deselects the image. If the image clicked hasn't been selected, it checks whether a position has been set. If a position has been set, it swaps the target (the image just clicked) with the image previously clicked. Otherwise, it sets the image clicked as the position (and then the next click will cause the images to swap).

setting an image object on iframe using javascript

I want to display an image in an iframe when I click that image inside that table. Problem is, the image that gets displayed inside the iframe is too small (too large images are not a problem for now). So I attempted to pass the image in a javascript function when it is clicked and perform the necessary resizes, but here I get another problem in setting the image object as the src of the iFrame. Any suggestions? Please guide me, I would save a lot of time if you can help.
Here is the javascript code I'm having problems with.
function resize(e){
var newImg = document.createElement('img');
newImg.src = document.getElementById(e).src;
newImg.width = '448';
newImg.height = '336';
document.getElementById('passTo').src = newImg.src; /*newImg doesn't work aswell*/
}
Here is my HTML code...
<tr>
<td colspan="2" height="336">
<iframe id = "passTo" name="A" src="Activity 6.html" style="width:100%; height:100%;" scrolling="no" marginheight="0" marginwidth="0">
<p>iframes are not supported by your browser.</p>
</iframe>
</td>
</tr>
<tr>
<td><img src = "index.jpg" id = "myimg" border="3" height="48" width="64" onclick="resize(myimg)"></img></td>
<td><img src = "index.jpg" id = "myimg2" border="3" height="48" width="64" onclick="resize(myimg2)"></img></td>
</tr>
I would suggest just setting the innerHTML of the iframe body:
function resize(e){
var imgURL = document.getElementById(e).src;
var iframe = document.getElementById('passTo');
var html = "<img width='448' height='336' src=" + imgURL + ">";
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.body.innerHTML = html;
}
Or, if you wanted to create the img object yourself and insert it, you could do it like this:
function resize(e){
var imgURL = document.getElementById(e).src;
var iframe = document.getElementById('passTo');
// get iframe document in cross browser way
var doc = iframe.contentDocument || iframe.contentWindow.document;
// create img object in the iframe's document.
var img = doc.createElement("img");
img.height = 336;
img.width = 448;
img.src = imgURL;
doc.body.appendChild(img);
}
There were several issues with what you were previously trying:
You were settings the iframe.src to an image URL. When doing that, you have no control over the height and width of the img object that the iframe creates and it has nothing to do with the other img object you had created.
You can't create an img object in one document and then use it in another document.
The easiest way to put some HTML in another document is be just setting HTML on it and letting the browser create the objects in the right document.
Also, keep in mind that you can only modify or read the DOM contents of an iframe if it's in the same domain as the window/frame your code is running in (which is OK in your example).

Change image on click

I have a table and I would like to change an image in its <td> when I click it but it must be URL of image that I determine before.
That URL of image I type to the link of the page(for example by click on img)
index.html?type=dog
Then the script will read variables from link. I will create variable to the script.
type = httpGetVars["type"]
Now when I click on where is img of cat, the script should replace cat.png for dog.png and I tried it in this way.
<img src="cat.png" onClick="document.write("<img src=\""+ type + ".png\">);
<img id="foo" src="cat.png />
Give that <img> an id - foo for example than:
document.getElementById('foo').src = type +".png";
You simply change the existing <img> src to the new image.
You can define the img like the following:
<img src="some_image_url.extension" onclick="switchImage(this)" />​
and then on the switchImage function you can check the current image and change to a different image:
var switchImage = function(image) {
if(image.src == dogImage) {
image.src = catImage;
} else {
image.src = dogImage;
}
};​
I've made a Sample Fiddle so you can see it running.

Categories