Change the order of images by clicking buttom [duplicate] - javascript

This question already has answers here:
Changing the order of elements
(4 answers)
Closed 8 years ago.
Help me to solve this trivial problem.
I need to change an image order within button_Click. How can I do this?
Actualy I need the **simplest** way, **no jQuery**.
Will be very grateful for piece of working code with explanation - It's a headache for me
[Here][1] is my code
PS I already got some advises, but all them conneted to jQuery
No jQuery
<div id="one">
<input id="b1" value="Change the image order" onclick="change_order()" type="button"/>
<h1 style="font-size: 12"> Header HeaderHeaderHeader</h1>
<p style="font-size:8"> text text text </p>
</div>
<div id="picContainer">
<img id="pict_01" src="http://heaversfarm.files.wordpress.com/2013/01/i-love-maths.jpg" />
<img id="pict_02" src="http://www.uplandsoutreach.org/wp-content/uploads/2013/04/20maths1.jpg" />
<img id="pict_03" src="http://www.milldamschool.ik.org/img/d666f5fc-db14-11de-a689-0014220c8f46-5812526.jpg" />
<img src="http://www.birdsontheblog.co.uk/wp-content/uploads/2010/05/maths.jpg" />
</div>

Hope you find the below code working as per your requirement.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button><br/>
<br/>
<img height="50" width="50" id="demo1" src="http://www.largeyellowbutton.com/largeyellowbutton.jpg"></img>
<br/>
<img height="50" width="50" id="demo2" src= "http://libn.com/wp-files/graphics/register-button_0.jpg"></img>
<br/>
<img height="50" width="50" id="demo3" src= "http://mygimptutorial.com/images/button-with-reflection/11.jpg"></img>
<script>
function myFunction() {
var temp=document.getElementById("demo1").src;
document.getElementById("demo1").src = document.getElementById("demo2").src;
document.getElementById("demo2").src = document.getElementById("demo3").src;
document.getElementById("demo3").src = temp;
}
</script>
</body>
</html>

Use the code which I have posted above in case you know the number of image inside your div. If your unsure about the number of images your going to add then use the below code.
<html>
<head>
<script>
function myFunction() {
var count=document.getElementById("picContainer").getElementsByTagName("img").length;
//below code captures the first image source before
//changing the image order. This is also used to assign as source to the
// last image tag.
var temp=document.getElementById("pict_01").src;
var i;
for(i=1;i<=count;i++)
{
//If value of i is equal to count then, assign the first image source
// captured in temp variable to the last image inside the div.
if(i==count){
document.getElementById("pict_0"+i).src=temp;
}
//below code assigns image in decreasing order.
document.getElementById("pict_0"+i).src = document.getElementById("pict_0"+(i+1)).src;
}
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value=" Change an image order"></input>
<br/>
<div id="picContainer">
<img id="pict_01" src="http://heaversfarm.files.wordpress.com/2013/01/i-love-maths.jpg" />
<img id="pict_02" src="http://www.uplandsoutreach.org/wp-content/uploads/2013/04/20maths1.jpg" />
<img id="pict_03" src="http://www.milldamschool.ik.org/img/d666f5fc-db14-11de-a689-0014220c8f46-5812526.jpg" />
<img id="pict_04" src="http://www.birdsontheblog.co.uk/wp-content/uploads/2010/05/maths.jpg" />
</div>
</body>
</html>

Related

Get image variable src attribute [duplicate]

This question already has answers here:
How to reach the element itself inside jQuery’s `val`?
(4 answers)
Closed last year.
I have an image inside a div and an input outside of the div, I'm trying to take each image source and put it inside the input's value, I want the image as a variable, how can I take the source of this variable and put it in the input's value?
var image = "img"
console.log('image');
$("input").val(image.attr('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/350x150">
</div>
<input type="text">
<div>
<img src="http://via.placeholder.com/300x150">
</div>
<input type="text">
<div>
<img src="http://via.placeholder.com/250x150">
</div>
<input type="text">
You could loop through them and get the source of everyone then affect it to the next input :
$('img').each(function() {
var image = $(this);
//Using the variable 'image'
image.closest("div").next("input").val( image.attr('src') );
//Or just like
$(this).closest("div").next("input").val( this.src );
});
$('img').each(function() {
var image = $(this);
image.closest("div").next("input").val(image.attr('src'));
})
input {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/350x150">
</div>
<input type="text">
<div>
<img src="http://via.placeholder.com/300x150">
</div>
<input type="text">
<div>
<img src="http://via.placeholder.com/250x150">
</div>
<input type="text">
It's really good practice to pack your logical component into a single DOM node. The way you have it structured, there's no logical connection between the image and the input, other than the fact that one is beside the other. Simply because Sheila sits in the cubicle beside mine doesn't mean we're functioning together.
Instead, see what I've got below -- each image/input is contained in a div. The only image that an input should see is right in its same container. Now Sheila is in the same cubicle as me, we're now working on the same thing and can reference each other.
And, rather than the image and the input needing to know about each other, I'm asking the container itself to set those values. By doing this, the pieces are a little more loosely coupled.
var containerEls = $(".container");
containerEls.each(function(){
var imgEl = $(this).find("img");
var inputEl = $(this).find("input[type=text]");
inputEl.val(imgEl.attr("src") );
});
input {
width: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div>
<img src="http://via.placeholder.com/350x150">
</div>
<input type="text">
</div>
<div class="container">
<div>
<img src="http://via.placeholder.com/300x150">
</div>
<input type="text">
</div>
<div class="container">
<div>
<img src="http://via.placeholder.com/250x150">
</div>
<input type="text">
</div>
Use val(function) to loop through all the inputs individually Then traverse to the instance specific image to return the value
$("input").val(function() {
return $(this).prev().find('img').attr('src');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/350x150">
</div>
<input type="text">
<div>
<img src="http://via.placeholder.com/300x150">
</div>
<input type="text">
<div>
<img src="http://via.placeholder.com/250x150">
</div>
<input type="text">

How to make a simple recognizing game using may symbols

Hi I am new to this and still learning haha so go easy on me.
I am trying to make a simple recognizing game using map symbols as the images.
I have got the start button when clicked will ask you a question but cannot seem to get a random picture to appear as well. I also what the grey stars to light up every time the user selects the right button/symbol.
Here is the code:
<!DOCTYPE html>
<style>
body{ background-color: lightblue; }
</style>
<html>
<head>
<title>OS Map Symbols</title>
<meta charset="utf-8" />
</head>
<body>
<p> <input onclick="btnStart(); displayRandomImage();" type="button" value="Start" /> </p>
<input id="btnTrain" type="button" value="Train Station" disabled="disabled"/>
<input id="btnBus" type="button" value="Bus Station" disabled="disabled"/>
<input id="btnYouth" type="button" value="Youth Hostel" disabled="disabled"/>
<input id="btnFootpath" type="button" value="FootPath" disabled="disabled"/>
<input id="btnBridle" type="button" value="Bridleway" disabled="disabled"/>
<input id="btnWorship" type="button" value="Place of Worship" disabled="disabled"/>
<input id="btnHouse" type="button" value="Public House" disabled="disabled"/>
<input id="btnCar" type="button" value="Car Park" disabled="disabled"/>
<input id="btnRoad" type="button" value="Road" disabled="disabled"/>
<input id="btnPillar" type="button" value="Triangulation Pillar" disabled="disabled"/>
<center> <p> <p id="paragrapgh"> </p> </center>
<center> <div class="contents" id="content"></div> </center>
<img id="imgTrain.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_TS.jpg" width="100" height="100" style="display:none;"/>
<img id="imgBus.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_BS.jpg" width="100" height="100" style="display:none;"/>
<img id="imgYouth.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_YH.jpg" width="100" height="100" style="display:none;"/>
<img id="imgFootpath.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_FP.jpg" width="100" height="100" style="display:none;"/>
<img id="imgBridle.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_BW.jpg" width="100" height="100" style="display:none;"/>
<img id="imgWorship.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_PW.jpg" width="100" height="100" style="display:none;"/>
<img id="imgHouse.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_PH.jpg" width="100" height="100" style="display:none;"/>
<img id="imgCar.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_CP.jpg" width="100" height="100" style="display:none;"/>
<img id="imgRoad.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_RD.jpg" width="100" height="100" style="display:none;"/>
<img id="imgPillar.jpg" img src="C:\Users\ekene\OneDrive\Pictures\MapSym_TP.jpg" width="100" height="100" style="display:none;"/>
<img src="C:\Users\ekene\OneDrive\Pictures\star-g.gif" img id="imgStar1" />
<img src="C:\Users\ekene\OneDrive\Pictures\star-g.gif" img id="imgStar2" />
<img src="C:\Users\ekene\OneDrive\Pictures\star-g.gif" img id="imgStar3" />
<img src="C:\Users\ekene\OneDrive\Pictures\star-g.gif" img id="imgStar4" />
<img src="C:\Users\ekene\OneDrive\Pictures\star-g.gif" img id="imgStar5" />
</body>
</html>
<script>
function btnStart() {
var x = document.getElementById("paragrapgh");
x.style.fontSize = "25px";
x.style.color = "red";
document.getElementById("paragrapgh").innerHTML = "What Is This Symbol?";
}
function displayRandomImage(){
var Images1 = new Array();
Images1[0]= "C:\Users\ekene\OneDrive\Pictures\MapSym_TS.jpg"
Images1[1]= "C:\Users\ekene\OneDrive\Pictures\MapSym_BS.jpg"
Images1[2]= "C:\Users\ekene\OneDrive\Pictures\MapSym_YH.jpg"
Images1[3]= "C:\Users\ekene\OneDrive\Pictures\MapSym_BW.jpg"
Images1[4]= "C:\Users\ekene\OneDrive\Pictures\MapSym_PH.jpg"
Images1[5]= "C:\Users\ekene\OneDrive\Pictures\MapSym_RD.jpg"
Images1[6]= "C:\Users\ekene\OneDrive\Pictures\MapSym_FP.jpg"
Images1[7]= "C:\Users\ekene\OneDrive\Pictures\MapSym_PW.jpg"
Images1[8]= "C:\Users\ekene\OneDrive\Pictures\MapSym_CP.jpg"
Images1[9]= "C:\Users\ekene\OneDrive\Pictures\MapSym_TP.jpg"
var random = Images1[Math.floor(Math.random() * Images1.length)];
document.getElementById("content").innerHTML = random;
}
</script>
You were very close. The issue you're encountering can be solved using the addEventListener method of connecting events to elements. In this case, adding an id to your start button and firing the events when clicked would look like this
JSFIDDLE
HTML
<input id="startButton" type="button" value="Start" />
JS
var startButton = document.getElementById('startButton');
startButton.addEventListener('click', function(){
btnStart();
displayRandomImage();
});
It's worth mentioning you have a number of HTML syntax issues including unclosed tags, style and script tags outside of the html element, using . in id attributes, and using deprecated tags like center.
Unfortunately, because you have locally linked images, im not sure if you're asking how to make the gif items animate again (Can you control GIF animation with Javascript?) or if you're asking about swapping image src using js (Programmatically change the src of an img tag)
From a coding perspective, the way you're going about trying to link up images to the buttons could be made far simpler for yourself by starting with a JS object, and generating items from there, especially as you have a consistent path to images. Something like this: JSFIDDLE

Add href link to Image that has been displayed via js click

Similar to a question I asked recently but the previous was using mouse over so was rubbish for touch screen.
This is 3 divs with images. on click they individually change to a second image and reset the other 2 to a standard image. this all works ok.
But when the second image in any of the divs is active i would like to be able to click this image and navigate to a different page.
Clearly adding href to the html just navigates and ignores the JS effect.
Thanks for reading.
$(document).ready(function(){
$('#s1').click(function(){
$('#s1').attr('src', 'images/object/click-1.png');
$('#s2').attr('src', 'images/object/standard-2.jpg');
$('#s3').attr('src', 'images/object/standard-3.jpg');
});
$('#s2').click(function(){
$('#s1').attr('src', 'images/object/standard-1.jpg');
$('#s2').attr('src', 'images/object/click-2.png');
$('#s3').attr('src', 'images/object/standard-3.jpg');
});
$('#s3').click(function(){
$('#s1').attr('src', 'images/object/standard-1.jpg');
$('#s2').attr('src', 'images/object/standard-2.jpg');
$('#s3').attr('src', 'images/object/click-3.png');
});
});
<div id="section3" class="container-fluid" align="center">
<div class="row row-centered ">
<div id="top-box-1" class="col-sm-4">
<img src="images/object/standard-1.jpg" class="std" id="s1" width="300" height="300"/>
</div>
<div id="top-box-2" class="col-sm-4">
<img src="images/object/standard-2.jpg" class="std "id="s2" width="300" height="300"/>
</div>
<div id="top-box-3" class="col-sm-4">
<img src="images/object/standard-3.jpg" class="std" id="s3" width="300" height="300"/>
</div>
</div>
</div>
You can see if the src now contains 'click'. if not then swap the src and return false to stop the href:-
$('#s1').click(function(e) {
if (!$(this).is('[src*="click"]')) {
$('#s1').attr('src', 'images/object/click-1.png');
$('#s2').attr('src', 'images/object/standard-2.jpg');
$('#s3').attr('src', 'images/object/standard-3.jpg');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section3" class="container-fluid" align="center">
<div class="row row-centered ">
<div id="top-box-1" class="col-sm-4">
<a href="http://stackoverflow.com/">
<img src="images/object/standard-1.jpg" class="std" id="s1" width="300" height="300" />
</a>
</div>
<div id="top-box-2" class="col-sm-4">
<a href="http://stackoverflow.com/">
<img src="images/object/standard-2.jpg" class="std " id="s2" width="300" height="300" />
</a>
</div>
<div id="top-box-3" class="col-sm-4">
<a href="http://stackoverflow.com/">
<img src="images/object/standard-3.jpg" class="std" id="s3" width="300" height="300" />
</a>
</div>
</div>
</div>
To break this down: if (!$(this).is('[src*="click"]')) {
$(this).is allows you to check this against a selector, returning a boolean (true) if it does.
'[src*="click"]' is the selector to determine if the src attribute contains 'click'. Where the * means contains anywhere. There are other combinations like ^= for starts with.
Therefore $(this).is('[src*="click"]') means true if the src has 'click'. But you need to invert this to not contains. That's what the ! is for, meaning if this (the clicked element) has not got 'click' in the src.
Since you're already handling the click event, you'll likely want to perform this logic in that same event. Something structurally like this:
if (/* some condition */) {
window.location.href = someUrl;
}
I guess you'd need to define what that condition is. Would it be based on the current src of the image? Something like this?:
if ($(this).attr('src') === 'images/object/click-1.png') {
window.location.href = someUrl;
}
(You'd also have to define what someUrl is, of course.)

HTML and Javascript picture change on button click

I am trying to get these pictures to swap when the button is pressed, the pictures are local to my computer and need to change in sequence. When I press the button, it just generates a new picture, I need them to interchange
<html>
<head>
<script>
var imgs=document.images;
function changeLight() {
var firstImage = imgs[0].src + "";
for(var i=0; i<imgs.length-1; i++){
imgs[i].src=imgs[i+1].src+"";
}
imgs[imgs.length-1].src=firstImage;
}
</script>
</head>
<body>
<div id="splash">
<img src="Traffic Light Red.gif" alt="" id="mainImg">
</div>
<body>
<div id="wrapper">
<div>
<img id="image" src="images/test" />
<br><br><br>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="Traffic Light Yellow.gif" hidden />
<img src="Traffic Light Green.gif" hidden />
<img src="Traffic Light Yellow2.gif" hidden />
</div>
</div>
</body>
Here is some code. It works by comparing the src attributes of the hidden images, not a very elegant technique, but it works. This method will also break if you add images before the last hidden image, so use with care.
Also remember to rename the files so that they have no spaces. On the web, spaces get turned into %20s when being requested, which tends to break things :)
Anyways, here’s the code.
<!doctype html>
<html>
<body>
<div id="splash">
<img src="TrafficLightRed.gif" alt="" id="mainImg">
</div>
<div id="wrapper">
<div>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="TrafficLightRed.gif" hidden>
<img src="TrafficLightYellow.gif" hidden>
<img src="TrafficLightGreen.gif" hidden>
</div>
</div>
<script>
function changeLight() {
var currentImg = document.getElementById("mainImg");
for(var i=1;i<3;i++) {
if(document.images[i].src == currentImg.src) {
currentImg.src = document.images[i + 1].src;
return;
}
}
currentImg.src = document.images[1].src;
}
</script>
</body>
</html>
A more robust technique would be to store an array of image links in your JavaScript, instead of the hacky hidden images. Brownie points for implementing that!
so you mean first come as third, second as first and third as second??
and again the same on next click??
check the fiddle http://jsfiddle.net/stdeepak22/hax3d8cv/
$(document).ready(
function(){
$('#nextImage').click(function(){
var firstImage = $('#AllImages img:first');
$(firstImage).remove();
$('#AllImages').append(firstImage);
});
});
UPDATE
pure JavaScript. for those who says "jQuery for just this? my my" ;)
http://jsfiddle.net/stdeepak22/0mcLcozk/
function f(){
var allImage = document.getElementById('AllImages');
var firstImage = allImage.getElementsByTagName('img')[0];
allImage.removeChild(firstImage);
allImage.appendChild(firstImage);
}
Refer the script :
<html>
<head>
<script>
var imgs=document.getElementsByTagName('img');
var init = 3;
console.log(imgs[2].src);
function changeLight(){
var target = document.getElementById('imaget');
var firstImage = imgs[0].src + "";
if(init < 5 ){
target.src = imgs[init].src;
init = init +1;
}
else{
init = 3;
target.src = imgs[init].src;
}
}
</script>
</head>
<div id="splash">
<img src="Traffic Light Red.gif" alt="" id="mainImg">
</div>
<body>
<div id="wrapper">
<div>
<img id="imaget" src="images/test" />
<br><br><br>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="Traffic Light Yellow.gif" hidden />
<img src="Traffic Light Green.gif" hidden />
<img src="Traffic Light Yellow2.gif" hidden />
</div>
</div>
</body>
This works for me. I would like to suggest you to use array values (image srcs) set in javascript instead of using hidden images.

Getting the Id attribute from an Image in a div

I have a div that contains 1 to many images with next and previous image buttons. When a user clicks the next/previous button the current image style is changed from display:block to display:none using jquery. I need to get the ID attribute from the current image that is showing ie. has the display:block style applied.
<div id="propPhotos" name="propPhotos">
<div id="propPhotsDivList">
<div id="imageNameId0" style="display:block">
<img src="/PropertyImages/1/171fc210b4584f41936a078c4176c7e0.jpg" height="200" width="200" id="3"/>
</div>
<div id="imageNameId1" style="display:none">
<img src="/PropertyImages/1/114810f0067749eda8049d2f8269dd00.jpg" height="200" width="200" id="4"/>
</div>
<div id="imageNameId2" style="display:none">
<img src="/PropertyImages/1/8.jpg" height="200" width="200" id="15"/>
</div>
<div id="imageNameId3" style="display:none">
<img src="/PropertyImages/1/e8f182ab645549b399cebc67ed996d151.jpg" height="200" width="200" id="25"/>
</div>
</div>
<div>
<div class="row">
<input type="button" id="NextImage" value="Next Image" onclick="ImageNext()" /><input type="button" id="PrevImage" value="Previous Image" onclick=" ImagePrev()" />
</div>
<div class="row">
<button type="button" class="AddImage">Add Image</button><button type="button" class="RemoveImage">Remove This Image</button>
</div>
</div>
This is the path I am currently on which is in the next and previous image click handlers.
CurrentImageId = document.getElementById("imageNameId" + id).children('img').attr('id');
So when the user clicks either button its supposed to assign the id value to the CurrentImageId. This does not work for one and does not help on the initial load when neither next or previous image buttons have been clicked.
Well, there are a few different ways as far as the initial load is concerned. Here are a couple of examples:
Using the :visible selector:
var currentImageId = $('#propPhotsDivList > div:visible > img').prop('id');
Or perhaps combined with filter():
var currentImageId = $('#propPhotsDivList img').filter(function(){
return $(this).parent('div').is(':visible');
}).prop('id');
If the divs are hidden and shown correclty using your click handlers, you can use the same functionality inside them as well.
$('#propPhotsDivList').children('div:not(:hidden)').attr('id');

Categories