My goal is to randomly change an image by clicking on a button. I have found a snippet that does that but I wanted to train my skills and work my way through it, this is what I got so far:
When I click the button, with the variable on line 11, nothing happens, but when I put the URL instead of the variable (copied from the console from line 22), it goes to the according picture. I don't get it...
When my "imageCount" is full, I get an error
var imageCount = [];
var image = ["img/01.jpg", "img/02.jpg", "img/03.jpeg", "img/04.jpeg"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "\"url('" + image[rand] + "')\""
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
} else if (imageCount.length === image.length) {
imageCount = 0;
} else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
<link href="./style/main.css" rel="stylesheet">
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Two things stop your demo code from working:
#imageWrapper has no height, so the image is not displayed (probably only because your page's CSS is missing)
You reset the imageCount variable to 0 instead of []
var imageCount = [];
var image = ["//baconmockup.com/300/199/", "//baconmockup.com/300/200/", "//baconmockup.com/300/201/", "//baconmockup.com/300/202/"];
function changeImage() {
var rand = Math.floor(Math.random() * image.length);
var imageNumber = "url('" + image[rand] + "')"
if (imageCount.indexOf(rand) === -1) {
imageCount.push(rand);
document.getElementById("imageWrapper").style.backgroundImage = imageNumber;
}
else if (imageCount.length === image.length) {
imageCount = [];
}
else {
changeImage();
}
console.log(imageNumber);
console.log(imageCount.indexOf(rand));
console.log(image[rand]);
console.log(imageCount);
}
#imageWrapper {
height: 200px;
outline: solid black 1px;
}
<div class="wrapper">
<div class="buttonWrapper">
<button class="button" onclick="changeImage()">Next Pic</button>
</div>
<div id="imageWrapper">
<!--<img src="./img/02.jpg" alt="" id="random">-->
</div>
</div>
Related
I want each div background color to be changed by each different color input of color picker.
if I choose red in input 1, I want div right below of that input tag's background color to be red
and if I choose blue in input 2, I want div right below of that input tag's background color to be blue.
Right now, it's changing both of divs.
codes are below
var colorSelector;
var defaultColor = "#0000ff";
/**when page loads**/
window.addEventListener("load", startup, false);
function startup() {
var content_color1 = document.querySelector("#content_color1");
var content_color2 = document.querySelector("#content_color2");
/**select input for variable **/
colorSelector = document.querySelectorAll(".base");
var i = 0;
while (i < colorSelector.length) {
/**default input*/
colorSelector[i].value = defaultColor;
colorSelector[i].addEventListener("change", update, false);
i = i + 1;
}
}
function update(event) {
var i = 0;
while (i < colorSelector.length) {
if (colorSelector[0].selected = true) {
content_color1.style.backgroundColor = event.target.value;
};
if (colorSelector[1].selected = true) {
content_color2.style.backgroundColor = event.target.value;
};
i = i + 1;
}
}
<input type="color" class="base ct1">
<div id="content_color1">
cc1
</div>
<input type="color" class="base ct2">
<div id="content_color2">
cc2
</div>
One easy way is to tie the color picker to its "content" dive by way of a data-* attribute:
<input type="color" class="base ct1" data-content="#content_color1">
<div id="content_color1">
cc1
</div>
Then, on update use this to find the element and update it as needed:
function update(event) {
var content = document.querySelector(event.target.dataset.content)
content.style.backgroundColor = event.target.value;
}
Live example:
var colorSelector;
var defaultColor = "#0000ff";
/**when page loads**/
window.addEventListener("load", startup, false);
function startup() {
/**select input for variable **/
colorSelector = document.querySelectorAll(".base");
var i = 0;
while (i < colorSelector.length) {
/**default input*/
colorSelector[i].value = defaultColor;
colorSelector[i].addEventListener("change", update, false);
i = i + 1;
}
}
function update(event) {
var content = document.querySelector(event.target.dataset.content)
content.style.backgroundColor = event.target.value;
}
<input type="color" class="base ct1" data-content="#content_color1">
<div id="content_color1">
cc1
</div>
<input type="color" class="base ct2" data-content="#content_color2">
<div id="content_color2">
cc2
</div>
I don't know if this help
var colorSelector = document.querySelectorAll('.base');
var div1 = document.getElementById('content_color1');
var div2 = document.getElementById('content_color2');
var divs = [div1, div2];
for(let i = 0; i < colorSelector.length; i++){
colorSelector[i].addEventListener('change',() => {
divs[i].style.backgroundColor = colorSelector[i].value;
});
}
<input type="color" class="base ct1">
<div id="content_color1">
cc1
</div>
<input type="color" class="base ct2">
<div id="content_color2">
cc2
</div>
i want to increment index number of the image to actually get the size of the current image each time i click the button here is the code:
var next = document.querySelector("#nextBtn");
var prev = document.querySelector("#prevBtn");
var imgContainer = document.querySelector(".imgContainer");
let img = document.querySelectorAll(".imgContainer > img");
i want this var imgIndex = 0; to increment and store the new value which is incremented.
let size = img[imgIndex].clientWidth;
next.addEventListener('click', slideImg);
function slideImg() {
imgContainer.style.transform = "translateX(" + (-size) + "px)";
imgIndex++;
}
Refer this code.
You may not used the image index top of your function / global value. That's what it is again starts from zero.
function slideImg() {
var next = document.querySelector("#nextBtn");
var prev = document.querySelector("#prevBtn");
next.addEventListener('click', slideImg1);
}
var imgIndex = 0;
function slideImg1() {
var imgContainer = document.querySelector(".imgContainer");
let img = document.querySelectorAll(".imgContainer > img");
let size = img[imgIndex].clientWidth;
alert(imgIndex);
img[imgIndex].style.transform = "translateX(" + (-size) + "px)";
imgIndex++;
}
</script>
<body onload="slideImg()">
<input type="button" id="nextBtn" value="+" />
<input type="button" id="prevBtn" value="+" />
<div class="imgContainer">
<img src="file" />
<img src="file" />
</div>
</body>
I'm working on a slot machine game where i take 3 random numbers and assign them to different images.
However, I can't get my images to display when you click the button to play the game.
I have the stock images there but when you click SPIN it should replace them with new images based on random numbers.
How can I get the new images to display?.
My code:
<html>
<head>
<title>Slots</title>
<link href="../style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="random.js">
function spinslots() {
var lemon = document.getElementById('lemon.jpg');
var donut = document.getElementById('donut.jpg');
var cherry = document.getElementById('cherry.jpg');
var bar = document.getElementById('bar.jpg');
var random_1;
random_1= Math.floor((Math.random()*4 )+ 1);
var random_2;
random_2 = Math.floor((Math.random()*4 )+ 1);
var random_3;
random_3 = Math.floor((Math.random()*4 )+ 1);
if (random_1 == 1) {
document.getElementById("slot_1").src = "lemon.jpg";
}
if (random_1 == 2) {
document.getElementById("slot_1").src = "donut.jpg";
}
if (random_1 == 3) {
document.getElementById("slot_1").src = "cherry.jpg";
}
if (random_1 == 4) {
document.getElementById("slot_1").src = "bar.jpg";
}
if (random_2 == 1) {
document.getElementById("slot_2").src = "lemon.jpg";
}
if (random_2 == 2) {
document.getElementById("slot_2").src = "donut.jpg";
}
if (random_2 == 3) {
document.getElementById("slot_2").src = "cherry.jpg";
}
if (random_2 == 4) {
document.getElementById("slot_2").src = "bar.jpg";
}
if (random_3 == 1) {
document.getElementById("slot_3").src = "lemon.jpg";
}
if (random_3 == 2) {
document.getElementById("slot_3").src = "donut.jpg";
}
if (random_3 == 3) {
document.getElementById("slot_3").src = "cherry.jpg";
}
if (random_3 == 4) {
document.getElementById("slot_3").src = "bar.jpg";
}
if (random_1 == random_2 == random_3) {
alert("Congradulations, you won!");
}
}
</script>
</head>
<body>
<h1>Test your luck! Click the SPIN button</h1>
<p><button value="Spin" onclick="spinslots();"> SPIN </button></p>
<p>
<div class="SlotDiv" id="div_1"><image id="slot_1" src="images/lemon.jpg"></image></div>
<div class="SlotDiv" id="div_2"><image id="slot_2" src="images/cherry.jpg"></image></div>
<div class="SlotDiv" id="div_3"><image id="slot_3" src="images/bar.jpg"></image></div>
</p>
<p>Credits: <div class="OutputBox" type="numeric" id="Credits" size="10">20</div></p>
</body>
</html>
A few things you can improve about the code:
Don't use both src and content in your <script> tag, as this won't work.
Your getElementById calls should use the value from the id attribute, not the src.
You can set the initial value in the declaration line. i.e. var random_1 = Math.floor(...
Use === for comparing values
a === b === c should be a === b && b === c (thanks #jonas-h)
You should reduce code duplication, the code has the same logic repeated multiple times.
You should use <img> not <image> since the latter is obsolete
Since <img> elements have no content, you can use the short version to close them: <img src="..." />
<p> tags cannot contain block (div) elements inside, use divs instead.
Example of refactored code:
function spinslots() {
const images = [
// lemon:
'https://cdn.pixabay.com/photo/2012/04/03/15/07/lemon-25244_960_720.png',
// donut:
'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Simpsons_Donut.svg/1024px-Simpsons_Donut.svg.png',
//cherry:
'https://cdn.pixabay.com/photo/2013/07/13/10/23/cherries-157113_960_720.png',
//bar:
'https://cdn.pixabay.com/photo/2012/04/26/20/00/jackpot-42993_960_720.png',
];
const random_1 = Math.floor(Math.random() * 4);
const random_2 = Math.floor(Math.random() * 4);
const random_3 = Math.floor(Math.random() * 4);
document.getElementById("slot_1").src = images[random_1];
document.getElementById("slot_2").src = images[random_2];
document.getElementById("slot_3").src = images[random_3];
if (random_1 === random_2 && random_1 === random_3) {
alert("Congratulations, you won!");
}
}
.SlotDiv {
display: inline-block;
width: 100px;
height: 100px;
}
.SlotDiv img {
width: 100%;
}
<html>
<head>
<title>Slots</title>
</head>
<body>
<h1>Test your luck! Click the SPIN button</h1>
<div>
<button value="Spin" onclick="spinslots();"> SPIN </button>
</div>
<div>
<div class="SlotDiv" id="div_1">
<img id="slot_1" src="images/lemon.jpg" />
</div>
<div class="SlotDiv" id="div_2">
<img id="slot_2" src="images/cherry.jpg" />
</div>
<div class="SlotDiv" id="div_3">
<img id="slot_3" src="images/bar.jpg" />
</div>
</div>
<p>Credits: <span class="OutputBox" type="numeric" id="Credits" size="10">20</span></p>
</body>
</html>
Further enhancements:
note that the alert shows before the images change, due to it being executed synchronously. You can delay the message for a better effect.
the images take some time to show in the initial load, you can preload the images to avoid this.
I have a function that picks a random number from 1 - 6 and then appends it to the DOM. I am trying to compare that number to numbers that are currently in a div in the DOM. So I stored those numbers in a var called cards. When I console.log() the var it returns an array. I converted that array to a string and then I retrieved the text. What is the best way to go about comparing the numbers? Should I do a for loop and if any of those numbers match one of the random numbers drawn take some action? Can some one show me an example of doing this? My code is below.
$(function(){
function dice1(){
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions').text(randomNumber);
return randomNumber;
}
function dice2(){
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions2').text(randomNumber);
return randomNumber;
}
$('#dice1').click(function() {
dice1();
var cards = $('#cards div');
var single = cards.toString();
console.log(cards.text());
if ($('#instructions').text() == cards.text()) {
console.log('match');
}
});
$('#dice2').click(function(){
dice2();
});
});
<section id="container">
<div id="cards">
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
<div id="5">5</div>
<div id="6">6</div>
<div id="7">7</div>
<div id="8">8</div>
<div id="9">9</div>
</div>
<section>
<button id="dice1">Roll dice1</button>
<button id="dice2">Roll dice2</button>
<div id="instructions"></div>
<div id="instructions2"></div>
</section>
</section>
Why not store the cards directly in an array like this:
var cards = [1,2,3,4,5,6,7,8,9];
Then do the comparison like this:
var number = parseInt($("#instructions").text());
if(cards.indexOf(number) >= 0)
console.log("Number found");
else
console.log("Number not found");
If you really want to do it your way, you can do this:
$(".cards div").each(function(){
var number = parseInt($("#instructions").text());
var card = parseInt($(this).text());
if(card == number)
console.log("Number found");
});
Well you could indeed do it with a for loop:
$('#dice1').click(function() {
var random_number = dice1();
var cards = $('#cards div');
for(var i = 0; i < cards.length; i++ ) {
if($(this).html() == random_number) {
alert('Do something!');
}
}
console.log(cards.text());
if ($('#instructions').text() == cards.text()) {
console.log('match');
}
});
But you could also directly match to the ID you've set:
$('#dice1').click(function() {
var random_number = dice1();
var card = $('#cards div[id='+random_number+']');
if(card.length > 0) {
alert('Do something!');
}
});
Remember though, that the ID attribute can not start with a number, so I would create my own attribute here:
<div id="cards">
<div data-number="1">1</div>
<div data-number="2">2</div>
<div data-number="3">3</div>
<div data-number="4">4</div>
<div data-number="5">5</div>
<div data-number="6">6</div>
<div data-number="7">7</div>
<div data-number="8">8</div>
<div data-number="9">9</div>
</div>
And then use jQuery like so:
$('#dice1').click(function() {
var random_number = dice1();
var card = $('#cards div[data-number='+random_number+']');
if(card.length > 0) {
alert('Do something!');
}
});
You can do something like this:
New JS:
$(function () {
function dice1() {
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions').text(randomNumber);
return randomNumber;
}
function dice2() {
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions2').text(randomNumber);
return randomNumber;
}
$('#dice1').click(function () {
var num1 = dice1();
$('#cards div').each(function (index,item) {
if ($(item).text() == num1) {
$(item).css("color", "red");
}
});
$('#dice2').click(function () {
dice2();
});
});
});
Fiddle example
I just learned a way of doing it that solves it dynamically and personally I think it's easier to follow.
<div data-hook="cards" id="cards">
<div data-value="1" id="1">1</div>
<div data-value="2" id="2">2</div>
<div data-value="3" id="3">3</div>
<div data-value="4" id="4">4</div>
<div data-value="5" id="5">5</div>
<div data-value="6" id="6">6</div>
<div data-value="7" id="7">7</div>
<div data-value="8" id="8">8</div>
<div data-value="9" id="9">9</div>
</div>
$(function(){
function dice1(){
var randomNumber = Math.floor(Math.random() * 6) + 1;
$('#instructions').text(randomNumber);
return randomNumber;
}
$('#dice1').click(function() {
dice1();
$('[data-hook=cards] [data-value]').find('#instructions'); //'data-hook=cards] [data-value]' selects the element by attr'
var rolledNum = $('#instructions').text(),
selector = '[data-value=' + rolledNum + ']',
$card = $('[data-hook=cards]').find(selector);
//Instead of using an $.each or for loop to compare two numbers I am taking the random number and finding it on the div and then modifying the div.
console.log($card);
$card.css({'opacity':.2});
});
});
This should cycle through the <div> tags, but it isn't even showing the first one. It should show a "0", then 50ms later, show "1", then "2", and then "3". I get nothing.
Here's the HTML:
<div class="header" id="animation">
<div id="aniObj0" style="display: none;" onLoad="runAnimation();">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
The JavaScript:
var aniNum = 0;
var animationDelay = 50;
var frameDelay = 50;
function runAnimation()
{
Console.log("runningAnimation");
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if(aniObj != null){
if(prevObj != null){
aniObj.style.display = 'none;';
}
aniObj.style.display = 'block;';
aniNum++;
if(aniNum == 0){
setTimeout("runAnimation();", animationDelay);
}else{
setTimeout("runAnimation();", frameDelay);
}
}else{
aniNum = 0;
newAnimation();
}
}
You're very close. See code below (and comments in code).
HTML:
<div class="header" id="animation">
<!-- Removed onload="runAnimation()" - onload doesn't exist for a div -->
<div id="aniObj0" style="display: none;">0</div>
<div id="aniObj1" style="display: none;">1</div>
<div id="aniObj2" style="display: none;">2</div>
<div id="aniObj3" style="display: none;">3</div>
</div>
JavaScript:
var aniNum = 0;
var animationDelay = 500; //Changed to 500ms to you could see better
var frameDelay = 500; //Changed to 500ms to you could see better
function runAnimation()
{
var prevObj = document.getElementById('aniObj' + (aniNum - 1));
var aniObj = document.getElementById('aniObj' + aniNum);
if (aniObj != null) {
if (prevObj != null) {
aniObj.style.display = 'none;';
}
aniObj.style.display = '';
aniNum++;
if (aniNum == 0) {
//Changed setTimeout("runAnimation()", animationDelay); to
//setTimeout(runAnimation, animationDelay);
setTimeout(runAnimation, animationDelay);
} else {
setTimeout(runAnimation, frameDelay);
}
} else {
aniNum = 0;
newAnimation();
}
}
//You need to place this in a valid event. onload event of the body maybe?
runAnimation();
Here's a working fiddle.