Replace image with different image/button - javascript - javascript

within a function, I'm trying to replace a image/button with another image/button.
<img src="images/14.gif" id="ImageButton1" onClick="showLoad()">
<img src="images/getld.png" id="ImageButton2" alt="Get Last Digits" style="display:none;" onClick="showLock()" />
<script type="text/javascript" language="javascript">
function swapButton(){
document.getElementById('ImageButton1').src = document.getElementById('ImageButton2').src;
}
</script>
But I have the problem that there is two of the same button, (button 2) when it is replaced! (one at the top of the page, and one where it is meant to be). I was wondering if there is a way of getting rid of the extra button at the top, or creating the button element within the javascript function?
Thanks for any help.

You can remove an element in javascript using
var el = document.getElementById('id');
var remElement = (el.parentNode).removeChild(el);

You can hide the first button, not only change the image source. The code below shows one way of doing that.
<img src="images/14.gif" id="ImageButton1" onClick="swapButtons(false)" style="visibility: visible;" />
<img src="images/getld.png" id="ImageButton2" alt="Get Last Digits" style="visibility: hidden;" onClick="swapButtons(true)" />
<script type="text/javascript" language="javascript">
function swapButtons(show1) {
document.getElementById('ImageButton1').style.visibility = show1 ? 'visible' : 'hidden';
document.getElementById('ImageButton2').style.visibility = show1 ? 'hidden' : 'visible';
}
</script>

I'd suggest something akin to the following:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum).src;
}
else {
var next = document.getElementById(nextElemId).src;
}
elem.src = next;
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}​
JS Fiddle demo.
Edited to add that, while it is possible to switch the src attribute of an image it seems needless, since both images are present in the DOM. The alternative approach is to simply hide the clicked image and show the next:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum);
}
else {
var next = document.getElementById(nextElemId);
}
if (!next){
return false;
}
elem.style.display = 'none';
next.style.display = 'inline-block';
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}​
JS Fiddle demo.
Edited to offer an alternate approach, which moves the next element to the same location as the clicked image element:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum);
}
else {
var next = document.getElementById(nextElemId);
}
if (!next){
return false;
}
elem.parentNode.insertBefore(next,elem.nextSibling);
elem.style.display = 'none';
next.style.display = 'inline-block';
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}​
JS Fiddle demo.

Related

How to ssign Variable with div element's name

So I got multiple divs with different images embedded. Each one has its unique name attributes. I'm trying to apply the hover effect to each divs by changing the image source. I don't want to write multiple scripts, rather I'm trying to write a just one block of script that would effect every div.
<div id="div1" >
<img id="img1" name="img1" src="img1_up.jpg" />
</div>
<div id="div2">
<img id="img2" name="img2" src="img2_up.jpg" />
</div>...and so on
Now here is the script that I currently have for the rollover effects
<script>
var var1 = document.getElementById("div1");
var1.addEventListener("mouseover", changeImage1);
var1.addEventListener("mouseout", restoreImage1);
function changeImage1() {
document.getElementById("img1").src = "img1_ro.jpg";
}
function restoreImage1() {
document.getElementById("img1").src = "img1_up.jpg";
}
var var2 = document.getElementById("div2");
var2.addEventListener("mouseover", changeImage2);
var2.addEventListener("mouseout", restoreImage2);
function changeImage2() {
document.getElementById("img2").src = "img2_ro.jpg";
}
function restoreImage2() {
document.getElementById("img2").src = "img2_up.jpg";
}...and so on
</script>
I would like to use the name attributes from each images to create dynamic code to apply to all images. Here is what I have in mind but not sure the exact way to write it. PLEASE HELP
...
var dynamicVar = ????
dynamicVar.addEventListener("mouseover", changeImage();
dynamicVar.addEventListener("mouseout", restoreImage();
function changeImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_ro.jpg";
}
function restoreImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_up.jpg";
}
You can use loop to add event, don't need to specify id for each div:
var inputs = document.getElementsByTagName("div");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf('div') >= 0) {
inputs[i].addEventListener("mouseover", changeImage);
inputs[i].addEventListener("mouseout", restoreImage);
}
}
function changeImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_ro.jpg";
}
function restoreImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_up.jpg";
}
See on fiddle: Link
try this
var parent = document.getElementById("parent");
var childs = parent.getElementsByTagName('div');
for (var i = 0; i < childs.length; i++) {
(function () {
var e = childs[i];
e.addEventListener("mouseover", function () {
changeImage(e);
});
e.addEventListener("mouseout", function () {
restoreImage(e);
});
}());
}
function changeImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
alert(imgs[i].id);
}
}
function restoreImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = img_ro;
}
}
you can check this fiddle

(Javascript) SlideShow Not Working

Hello fellow stackoverflow members,
I've been trying to make a Slideshow. I've referenced from many other sites including this one but the pictures aren't showing up in the container element nor are the "prev" and "next" buttons functioning properly. I'd appreciate it if I got help! :)
my code:
var photos = newArray ();
photos[0] = "img/image(2).jpg";
photos[1] = "img/image(4).jpg";
photos[2] = "img/image(6).jpg";
photos[3] = "img/image(8).jpg";
photos[4] = "img/image(10).jpg";
photos[5] = "img/image(12).jpg";
photos[6] = "img/image(14).jpg";
photos[7] = "img/image(16).jpg";
photos[8] = "img/image(18).jpg";
photos[9] = "img/image(20).jpg";
photos[10] = "img/image(22).jpg";
photos[11] = "img/image(24).jpg"
//END OF PHOTOS ARRAY//
var i = 0;
var k = photos.length-1;
function next.onclick() {
var img= document.getElementById("image-container");
img.src = photos[i];
if (i < k ) {
i++;
}else {
i = 0; }
}
function prev.onclick() {
var img= document.getElementById("image-container");
img.src=photos[i];
if)i > 0) {i--;}
else {i = k; }
}
getImageArray = function(containerId) {
var containerElement = document.getElementById(container);
if (containerElement) {
var imageArray = containerElement.getElementById("container");
return photos[i];
} else {
return null;
}
}
this is what my slideshow looks like (it's broken)
http://prntscr.com/5dcfzq
The share button isn't important, I can make that work at least.
The main problem is that the pictures aren't showing and the back and foward buttons are messed up :'(
p.s ( I'm not sure if part of the reason is how I'm linking to the "next" or "back" functions with the div tag, because i'm this is how i'm doing it :
<div id = "back" onclick = "prev()"></div>
OK ... to summarize ...
1. var photos = newArray ();
There needs to be a space between new and Array, so ...
var photos = new Array();
2. function prev.onclick() { needs to be just function prev() {
3. Same with next.onclick() based on usage in HTML.
4. In prev() ... if)i > 0) {i--;} should be ...
if (i > 0) { i--; }
5. WRONG: Also in prev()' ... else should bei = k-1;`
6. DO NOT NEED Not sure why you have the getImageArray function at all.
7. This assumes there is an '' tag in the HTML.
UPDATE:
Here's the code that works ... this all goes in the body:
These are my assumptions in the body ...
<img id="image-container" />
<div id="back" onclick="prev()">Previous</div>
<div id="next" onclick="mext()">Next</div>
The script code MUST be at the end of the body ...
<script>
var photos = new Array ();
photos[0] = "img/image(2).jpg";
photos[1] = "img/image(4).jpg";
photos[2] = "img/image(6).jpg";
photos[3] = "img/image(8).jpg";
photos[4] = "img/image(10).jpg";
photos[5] = "img/image(12).jpg";
photos[6] = "img/image(14).jpg";
photos[7] = "img/image(16).jpg";
photos[8] = "img/image(18).jpg";
photos[9] = "img/image(20).jpg";
photos[10] = "img/image(22).jpg";
photos[11] = "img/image(24).jpg"
//END OF PHOTOS ARRAY//
// Here, I set the img variable so that it can be re-used.
// I also loaded the first image ...
var i = 0;
var k = photos.length-1;
var img = document.getElementById("image-container");
img.src = photos[i];
function next() {
img.src = photos[i];
if (i<k) {
i++;
} else {
i = 0;
}
}
function prev() {
img.src=photos[i];
if (i>0) {
i--;
} else {
i = k;
}
}
</script>

Change 2 image each other when click on them

i have a div with multiple images inside and i need to click on a random image then again click on a random picture and when i clicked the second image to change images with each other. All images are interchangeable.Heres what i've done so far:
EDIT FIDDLE: http://jsfiddle.net/w53Ls/5/
$("#image1").click(function(){
imagePath = $("#image2").attr("src");
if(imagePath == "http://s15.postimg.org/oznwrj0az/image.jpg"){
$("#image3").attr("src", "http://s21.postimg.org/ojn1m2eev/image.jpg");
}else{
$("#image4").attr("src", "http://s23.postimg.org/epckxn8uz/image.jpg");
}
});
EDIT: The code i have tryed for check function is in EDIT FIDDLE and with the alert i check src of pictures.Now i simply need to make a condition to alert something after i change all the pieces in order and found the whole picture.Any hint?
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
$("img.element").click(function(){
if (clickCount == 0)
{
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
}
else {
$("#"+lastImgId).attr("src",$(this).attr("src"));
$(this).attr("src",imgSrc)
clickCount = 0;
}
});
Updated
This let's you know when you're done with the puzzle
DEMO
var clickCount = 0;
var imgSrc;
var lastImgId;
// Function for Comparing Arrays
// source: http://stackoverflow.com/questions/7837456/
Array.prototype.compare = function (array) {
if (!array) return false;
if (this.length != array.length) return false;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] instanceof Array && array[i] instanceof Array) {
if (!this[i].compare(array[i])) return false;
} else if (this[i] != array[i]) {
return false;
}
}
return true;
}
$(document).ready(function () {
// Store the correct order first in an array.
var correctOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Randomize your images
var a = $("#puzzle > img").remove().toArray();
for (var i = a.length - 1; i >= 1; i--) {
var j = Math.floor(Math.random() * (i + 1));
var bi = a[i];
var bj = a[j];
a[i] = bj;
a[j] = bi;
}
$("#puzzle").append(a);
$("img.element").click(function () {
if (clickCount == 0) {
imgSrc = $(this).attr("src");
lastImgId = $(this).attr("id");
clickCount++;
} else {
$("#" + lastImgId).attr("src", $(this).attr("src"));
$(this).attr("src", imgSrc);
clickCount = 0;
// Get the current order of the images
var currentOrder = $("#puzzle > img").map(function () {
return $(this).attr("src");
}).get();
// Compare the current order with the correct order
if (currentOrder.compare(correctOrder)) alert("Puzzle completed");
}
});
});
http://jsfiddle.net/w53Ls/2/
var counter = 0;
The code was improvised but works XD
you try improve it
Here is a new version of your jsfiddle that I think will do what you want.
It applies the same click handler to every object with the class swapable. Each time a swapable element is clicked, the handler checks whether another element was previously clicked first. If so, it swaps them. If not, it just remembers that this element is the first one.
var firstId = ''; // Initially, no element has been clicked first
var firstSrc = '';
// Apply the following function to every element with 'class="swapable"
$('.swapable').click(function(){
if (firstId !== '') { // There is already a first element clicked
// Remember the information of the currently clicked element
var secondId = $(this).attr('id');
var secondSrc = $(this).attr('src');
// Replace the currently clicked element with the first one
$('#' + secondId).attr('src', firstSrc);
// Replace the first one with the current one
$('#' + firstId).attr('src', secondSrc);
// Forget the first one, so that the next click will produce a new first
firstId = '';
firstSrc = '';
}
else // This is the first element clicked (this sequence)
{
// Remember this information for when a second is clicked
firstId = $(this).attr('id');
firstSrc = $(this).attr('src');
}
});

Javascript Dynamically added HTML

Please Look at the following code only the last image moves.
http://jsfiddle.net/u8Bg3/
But second one works
http://jsfiddle.net/u8Bg3/1/
As pointed by the Er144 even this works with jquery
http://jsfiddle.net/u8Bg3/14/
I also found out appendchild works but not innerhtml
The difference between two is that in first one html exits in second one it's dynamically created
HTML
<body>
<div class="racetrack" id="racetrack"></div>
<div id="track-tmpl" class="hide">
<div class="track"><div id="player{{ x }}" class="runner"></div></div>
</div>
</body>
JS
var position = [0,40,80,120,80],
racetrack = document.getElementById('racetrack');
track_tmpl = document.getElementById('track-tmpl').innerHTML;
function Players(ele, ptimeout)
{
this.el = ele;
this.i = 0;
this.iterations = 0;
this.stop = 0;
this.timeout = ptimeout;
this.position = 0;
this.animate = function(){
if(this.i !== 0){
this.move((this.position + 5), this.i);
}
if(!this.stop){
if(this.i < 5){
setTimeout(function(_this){
_this.i++;
_this.animate();
},this.timeout,this);
}
if(this.i==5){
this.iterations ++;
if(this.iterations < 50){
this.i = 0;
this.animate();
}
else{
this.el.style.backgroundPosition = '120px 0px';
}
}
}
};
this.start = function(){
this.stop = 0;
this.animate();
};
this.move = function(to,positionIndex){
this.position = to;
this.el.style.backgroundPosition = '-'+position[positionIndex]+'px 0px';
this.el.style.webkitTransform = 'translate('+to+'px)';
this.el.style.mozTransform = 'translate('+to+'px)';
}
}
function Game(noOfPlayers){
this.noOfPlayers = noOfPlayers;
this.players = new Array();
for (var i = 0; i < this.noOfPlayers ; i++){
racetrack.innerHTML = racetrack.innerHTML + track_tmpl.replace('{{ x }}', i);
this.players.push(new Players(document.getElementById('player' + i), (120 + i)));
/* issue here with dynamic added content*/
}
this.start = function(){
for (var i = 0; i < this.noOfPlayers; i++){
this.players[i].start();
}
};
}
var game = new Game(3);
game.start();
Why is that in dynamically added html only the last one moves
The issue is with creating the player(n) object inside the for loop along with the assignments to innerHTML using `+='. The modified fiddle: http://jsfiddle.net/u8Bg3/15/ works fine. Cheers for a good question!
var finalized_tracks= "" ;
for (var i = 0; i < this.noOfPlayers ; i++){
finalized_tracks += track_tmpl.replace('{{ x }}', i);
}
racetrack.innerHTML = racetrack.innerHTML + finalized_tracks;
for (var i = 0; i < this.noOfPlayers ; i++){
this.players.push(new Players(document.getElementById('player'+ i),(120+i)));
}
If you use the jquery:
var element = track_tmpl.replace('{{ x }}', i);
$(racetrack).append(element);
instead of the line where you change the innerHtml of racetrack div, all elements are moving.
However, I'm not sure, why...
theCoder has pretty much nailed the issue with your code there.
Just as an additional thought, you could manually build the necessary divs using javascript instead, it's more long winded however...
for (var i = 0; i < this.noOfPlayers ; i++){
var newTrack = document.createElement("div");
newTrack.id = "track"+i;
newTrack.className = "track";
var newPlayer = document.createElement("div");
newPlayer.id = "player"+i;
newPlayer.className = "runner";
newTrack.appendChild(newPlayer);
racetrack.appendChild(newTrack);
this.players.push(new Players(document.getElementById('player' + i), (120 + i)));
}

new content replacing the old one hide and show

I amd working with hiding and showing divs, which have different contents. When i click on a link, i want a div to be shown. But when i click on another link, i want the new content to replace the previous one. Right now, it falls under it instead of replacing it. Any solution?
Javascript
function show(){
var links = {
link1: "content1",
link2: "content2",
link3: "content3",
link4: "content4"
};
var id = event.target.id;
var a = document.getElementsByTagName("a");
document.getElementById(links[id]).style.visibility = 'visible';
}
function init(){
var divs = document.getElementsByTagName("div");
for (i = 0; i < divs.length; i++) {
if (divs[i].className == "div") {
divs[i].style.visibility = 'hidden';
}
}
var a = document.getElementsByTagName("a");
for(i = 0; i < a.length; i++){
a[i].onclick = show;
}
}
window.onload = init;
You need to run the block of code that hides them all before showing the one you want, every time.
Make this:
function hideAll() {
var divs = document.getElementsByTagName("div");
for (i = 0; i < divs.length; i++) {
if (divs[i].className == "div") {
divs[i].style.visibility = 'hidden';
}
}
Remove this code from init() and replace it with a call to hideAll() and add a call to hideAll() at the beginning of show().

Categories

Resources