All purpose image swap function - javascript

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).

Related

Remove image when clicked

Basically, I'm trying to create a game where the goal is to click on images so they disappear.
I've made a function that spawns one image on a random location on the screen. Then I've also made an interval so it spawns 15 images in random locations. Now I want the images to disappear when clicked on.
My thoughts on doing this were to make a "click" function, so if the images are clicked the "img.style.height = '0px';
However, I'm not getting this or anything to work.
Use
<img onclick="this.style.visibility = 'hidden'" src="..." />
if you want to leave the space occupied by the image, otherwise:
<img onclick="this.style.display = 'none'" src="..." />
If you need to remove the image from an array of objects, you need to define a function as well.
In your code:
img.setAttribute("onclick", "this.style.visibility = 'hidden'" );
or
img.setAttribute("onclick", "this.style.display = 'none'" );
After you insert all images in document, define a click listener for all images and hide images on click. A simple example here
function hide(el) {
el.style.display = 'none';
}
var imgs = document.getElementsByTagName("img");
for(let i = 0; i < imgs.length; i ++) {
imgs[i].addEventListener('click', function(e) {
hide(e.target);
});
}
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTgYxw854mGOAp8f16evj_WYw_Ph385nUVygQdxHvuD9b3ueJxT0A" id="1" alt="Mountain View 1">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8_MiTkMX9nLJ9udtnwOQekIrQwUQ9KMZiU4fLfI7YhXCyIGZn" id="2" alt="Mountain View 2">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRgR4KM-zrVRmfdGPf5bll9vq4uLw7FSLpTmHUf9-RkYZ92Ey8Q" id="3" alt="Mountain View 3">
Your code should change like this
function SpawnW() {
var img = document.createElement("img");
img.setAttribute("style", "position:absolute;");
img.setAttribute("src", "women3.png");
document.body.appendChild(img);
img.setAttribute("onclick", "this.style.display = 'none'");
// pictureNumber++;
}
SpawnW();
Hope this helps you.

Change image within div on image icon click

I have created a Javascript function which will allow me to change the image to another when the div is directly clicked but I am trying to get this function to work depending on which other image icon i select.
As you can see by the above image, i have a main div which contains a picture on browser load, and two further thumbnail divs which include different pictures, I want to create the function to change the main div if one of the smaller thumbnail divs are selected.
Current Javascript Function
function diffImage(img) {
if(img.src.match(/blank/)) img.src = "bognor.jpg";
else img.src = "images/bognor2.jpg";
}
Thanks in advance,
Sam
You would just use onclick event listeners on the icons and the function would change the large image to the image of the item clicked:
document.getElementById("icon1").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
document.getElementById("icon2").onclick = function() {
document.getElementById("mainImage").src = this.src;
}
If you happen to have several icons you could make an icon class and apply the event listener like so:
var icons = document.getElementsByClassName("icon");
for(var i=0; i<icons.length; i++) {
icons[i].onclick = function(){
document.getElementById("main").src = this.src;
}
}
Fiddle Example for using classes
Although it's easier in that case to use jQuery and simply attach the event handler doing $('.icon').click(function(){ ... }). Of course you are not required to do so.
I recently did something similar where I had a table underneath the feature image of just smaller thumnail images.
$(".browseTable").on('click', 'td', function () {
var thumbNail = $(this).parent('tr').find('img').attr('src');
var feature = $('#featureImg img').attr('src');
$('#featureImg img').fadeOut(400, function () {
$(this).fadeIn(400)[0].src = thumbNail;
});
});
You could put the url of the big image in a custom data-attribute on the thumb element, such as <img src="thumb1.png" data-bigsrc="image1.png" />. Then you can add an event to all thumbnails like this:
var thumbs = document.querySelectorAll('.thumbnail');
var mainImage = document.querySelector('#mainImage');
for(var i=0; i<thumbs.length; ++i) {
thumbs[i].addEventListener('click', function(e) {
mainImage.src = e.target.getAttribute("data-bigsrc");
});
}
If you have high quality images and actually want to make them load when the user clicks, you could also use a radio button for each image, with the value set to the URL of the big image. Make the radio buttons invisible and put the thumbnails inside labels. Then you can just bind an event listener to all radio buttons and make them change the main image URL based on the radiobutton value.
Or if you want all the images to load in advance, you should just make tons of big-small image pairs and make the big image only visible if the small image's radiobutton is clicked, making an all-css solution.
As an alternative, this uses vanilla JavaScript, and three different ways of storing/naming the image files are covered.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div id="divMainImage">
<img id="mainImage" src="/images/image01Main.jpg" alt="Main image" />
</div>
<div id="divThumbnails">
<img class="thumb" src="/images/image01.jpg" alt="image01 thumbnail" />
<img class="thumb" src="/images/image02.jpg" alt="image02 thumbnail" />
<img class="thumb" src="/images/image03.jpg" alt="image03 thumbnail" />
</div>
<script type="text/javascript">
// Name both small and large images the same but with a prefix or suffix depicting thumbnail/main:
// image01.jpg (image01small.jpg) or image01Main.jpg (image01.jpg)
// image02.jpg (image02small.jpg) or image02Main.jpg (image02.jpg) etc.
// Or use two folders - one with main images, the other with thumbnails - both files named the same,
// then swap the folder to use when getting the image.
// Then use the displayed thumbnails' class to load originals:
var thumbnails = document.getElementsByClassName("thumb");
var mainImage = document.getElementById("mainImage");
for (index in thumbnails)
{
thumbnails[index].onclick = function () {
// Depending on the way used use on of the following:
mainImage.src = this.src.replace('.jpg', 'Main.jpg');
// Or
// mainImage.src = this.src.replace('thumb.jpg', '.jpg');
// Or
// mainImage.src = this.src.replace('/images/small/', '/images/large/');
}
}
</script>
</body>
</html>

Change Image OnClick & OnMouseover

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.

change image and caption

I am trying to work out a way to change the text that goes along with an image that is changed with javascript...
var x = 0;
var images = new Array(".jpg", ".jpg", ".jpg", ".jpg", ".jpg");
var i = setInterval(auto, 10000);
function auto() {
x++;
if (x == images.length) x = 0;
document.getElementById('bigImage').src = images[x];
}
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
/* document.getElementById('mainimagetitle').innerHtml = imagetitle; */
}​​​
The commented part is how i suppose I could possibly change the text that goes with the image. How do i code the html. Should i use a with the id mainimagetitle?
If so, where and how do i add the different texts i want to show and hide?
As I see from your posting, this should do the job.
<img id="bigImage" src="img1.jpg" alt="" />
<div id="mainimagetitle"></div>
Be sure to add a (filled) src tag or you will get strange results in IE. As you start with the second image (x++ before the change) this will be no problem. Happy accident I think. ;-)
// Edit: Of course any element will do as long as you use the right id. But you didn't tell us what html you use (xhtml/html5/...).
You could potentially have another array that stores the captions for each of the images
var captions = ['Caption 1', 'Caption 2', ...];
Assuming the mainimagetitle is an id of a <p> element, you could do:
function changeImage(img, imagetitle) {
document.getElementById('bigImage').src = img;
document.getElementById('mainimagetitle').innerText = imagetitle;
}​​​
You can see the full example, based on your code here.

how to swap image on clicking on image?

Here I use two images. when i click once on the Sort_down.png image then it changes to Sort_up.png.
When I click on this image again it is not changing back to Sort_down.png, how can I achieve this ?
<script type="text/javascript">
function clkimg() {
var img = document.getElementById('stCodeDSC');
img.src = '../Images/sort_up.png';
}
</script>
<td width="11%" bgcolor="#C5DEFF" class="menu_header">
<div align="center" onclick="clkimg();" >
<img name="stCodeDSC" class="img" src="../Images/Sort_down.png" id="stCodeDSC">
</div>
</td>
Depending on the browser you're using, when the source of an image is set to a relative URL, reading it back will give you the absolute URL. If you want to use a toggle, you can check for a string in the source, for example:
function clkimg() {
var img = document.getElementById('stCodeDSC'),
nextImg = img.src.indexOf('up.png')>0 ? 'down':'up';
img.src = '../Images/sort_' + nextImg + '.png';
}
If the sort_up and sort_down images are actually icons just identifying the up or down state of the current sort, you can combine the two images into one and use them as a sprite that you display using CSS. More details will be available at https://stackoverflow.com/search?q=css+sprite
You aren't telling it to sort down. In your click code you'll need to test if the image is showing up or down and change it accordingly. Something like:
if(img.src === '../Images/sort_up.png')
img.src = '../Images/sort_down.png';
else
img.src = '../Images/sort_up.png';
Generally, however, this would be better handled by adding or removing a class on click and styling the class using css.

Categories