I am trying to get a whole page of images to change when I click a single button. Here is my current code. My issue right now is I can change one image just fine but when I add the code to change the second image it stops the first image from changing and also will not let the second image change back to its original image.
Here is my JavaScript
//First image
var imageSources = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources.length) {
index = 0;
}
document.getElementById("imagechangingid").src = imageSources[index];
index++;
});
//Second image
var imageSources1 = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
buttons.addEventListener('click', function() {
if (index === imageSources1.length) {
index = 0;
}
document.getElementById("imagechangingid2").src = imageSources1[index];
index++;
});
This is because you are overriding your first event listener when you write below code twice. one implementation (I am guessing the second one) will override the other
buttons.addEventListener('click', function() {}
if the same button click should change both images - you should handle it in same event handler.
var imageSources = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var imageSources1 = ["origonal-image.jpg","2ndimage.jpg"]
var buttons = document.getElementsByClassName("change-image")[0];
var index = 0;
var indexOne = 0;
buttons.addEventListener('click', function() {
if (index === imageSources1.length) {
index = 0;
}
document.getElementById("imagechangingid2").src = imageSources1[index];
index++;
if (indexOne === imageSources.length) {
indexOne = 0;
}
document.getElementById("imagechangingid").src = imageSources[indexOne];
indexOne++;
});
Related
i'd like to link a divblock with the current position within the for-loop
Problem: all DivBlock get the link with the last position of the loop
my code is like this:
for (var i = 1; i <= kundenAnzahl; i++) {
var block = document.createElement("div");
block.id = i.toString();
document.getElementById(i.toString()).addEventListener('click', function() {
location.href = 'server.html?kunde='+i
}, true);
change var to let because -> https://wesbos.com/for-of-es6/
and you can assign event listeners directly to new created div element, look this code
for (let i = 0; i < 5; i++) {
var block = document.createElement('div');
block.addEventListener('click', function() {
location.href = 'server.html?kunde='+i;
}, true);
document.body.append(block);
}
I am attempting to code a checkers game in JavaScript and I am having trouble with stopping images after one swap. In the current implementation (below) the images swap on click and then when you click on another part of the board (a table in this case) another 'piece' is placed. But then when you click again another is placed and another etc. I am trying to not have a piece be placed when you click again.
var imageSwaped = false;
function clickOnBlankSpace(object)
{
this.src="Directory/BlackPiece.png";
imageSwaped = true;
this.removeEventListener("click", clickOnBlankSpace);
return;
}
var BlackPieces = document.getElementsByClassName("BlackPiece");
var RedPieces = document.getElementsByClassName("RedPiece");
var BlankSpaces = document.getElementsByClassName("BlankSpace");
for(var j = 0; j<BlackPieces.length;j++)
{
var BlackPiece = BlackPieces[j];
BlackPiece.addEventListener("click", function()
{
this.src="Directory/BlackPieceH.png";
this.className ="BlackPieceH";
for(var j = 0; j<BlankSpaces.length;j++)
{
var BlankSpace = BlankSpaces[j];
if (!imageSwaped) BlankSpace.addEventListener("click", clickOnBlankSpace);
}
})
}
I'm creating a tool which generates a bunch of divs based on data I input into an array, however they all have the same class. The idea is that when one link is clicked it shows one of the ".catbox" divs and hides the rest.
All of these divs have the same class so I need to iterate through them, but I'm not quite sure how this is done with jQuery. Currently clicking on the last ".list" class triggers the on click event instead of all of them, and currently it shows all of the divs with the class ".catbox" instead of the corresponding one.
Here is the code:
var HTMLcatName = '<h1>%data%</h1>';
var HTMLcatImage = '<img id="cat" src="%data%">';
var HTMLcatCounter = '<p class="counter">Number of clicks: %data%</p>';
var HTMLcatList = '<p>%data%</p>'
var noCats = 'No cats selected m8';
var getCounterClass = document.getElementsByClassName("counter");
$(document).ready(function() {
cats.display();
$('.catbox').hide();
for (u = 0; u < cats.name.length; u++) {
formattedCatList = HTMLcatList.replace("%data%", cats.name[u]);
var listDiv = document.createElement('div');
listDiv.innerHTML = formattedCatList;
listDiv.className = "list";
$(".list").click(function() {
$(".catbox").toggle("slow");
});
$("body").prepend(listDiv);
}
});
var update = function() {
for (j = 0; j < getCounterClass.length; j++) {
getCounterClass[j].innerHTML = 'Number of clicks: ' + cats.clicks[j];
}
}
var cats = {
"name": ["Monte", "Jib"],
"image": ["images/monte.jpg", "images/jib.jpg"],
"clicks": [0, 0],
display: function () {
for (i = 0; i < cats.image.length; i++) {
formattedCatNames = HTMLcatName.replace("%data%", cats.name[i]);
formattedCatImages = HTMLcatImage.replace("%data%", cats.image[i]);
formattedCatCounter = HTMLcatCounter.replace("%data%", cats.clicks[i]);
var catDiv = document.createElement('div');
catDiv.className = "catbox";
catDiv.innerHTML = formattedCatNames + formattedCatImages + formattedCatCounter;
catDiv.querySelector('img').addEventListener('click', (function(catCountUp) {
return function() {
cats.clicks[catCountUp]++;
update();
};
})(i));
document.body.appendChild(catDiv);
}
},
}
The function I need help with is found within $(document).ready(function() {
Any help would be greatly appreciated.
The following can do it:
$(".list").on("click", function(){
$(this).find(".catbox").toggle("slow");
});
With $('.list') you get a group of elements of class list, so if you use $('.list').click(); you will bind the click event to just one element. You should use:
$(".list").each(function(){
$(this).click(function() {
$(".catbox").toggle("slow");
});
});
This code takes the background color from an array of divs and colors another div with it. My problem is that I can put any value from 0-2 (0-2 being the array value of the original div) in task1[i].style.background but when I put i so that the loop gives me the value specific to the one moused over it brakes. I cannot use JQuery, JavaScript only.
EDIT: I expect task1[i].style.background to be equal to the background color of the specific div it hovered over from the loop running through the array.
var task1 = document.querySelectorAll('.t1_colors');
var task1background = document.querySelector('#task1');
var white = function() {
task1background.style.background = 'white';
}
for (var i = 0; i < task1.length; ++i) {
task1[i].addEventListener('mouseover', function () {
colorize();
});
}
//Something wrong with i
var colorize = function() {
task1background.style.background = task1[i].style.background;
}
for (var i = 0; i < task1.length; ++i) {
task1[i].addEventListener('mouseout', function() {
white();
});
}
What do you expect the value of i to be when you use it in colorize?
task1background.style.background = task1[i].style.background;
When colorize executes inside mouseover event listener, all loops have already terminated because i value reached task1.length.
You have to capture the current i value.
Change it to
for (var i = 0; i < task1.length; ++i) {
task1[i].addEventListener('mouseover', (function (index) {
return function() { colorize(index); };
})(i));
}
and
var colorize = function(index) {
task1background.style.background = task1[index].style.background;
}
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');
}
});