Unique Array Values across Two Functions and Two Divs - javascript

I want to obtain different height values for each div in both the 'CardContainer' and 'Two' divs. I would like to randomize those values upon each click event without repeating any of the values in the array.
http://codepen.io/jlhanna/pen/oBjrov
HTML
<html>
<button id="press" type="Button" value="Shake">Test</button>
<div id="cardContainer"></div>
<div id="two"></div>
<div id="three"></div>
</html>
CSS
#cardContainer div {border:solid 1px black; width: 20px;}
#two {border:solid 1px black; width: 20px; position: absolute; top: 20px; left: 50px;}
button {display: block;}
JS
var balls90 = ['1px', '5px', '10px', '20px', '40px', '80px', '160px', '320px'];
var cardContainer= document.getElementById("cardContainer");
var two= document.getElementById("two");
var $all = $("#cardContainer").push(balls90);
var $next = $("#two").push(balls90);
function getNumbers() {
var player1 = new Array();
balls90.sort(function() {
return [Math.floor(Math.random() * balls90.length)];
});
$("#press").click(function() {
$("#cardContainer").empty();
});
document.getElementById("press").addEventListener('click',getNumbers,true);
for (var i = 1; i <= 4; i++) {
var div = document.createElement("div");
div.style.height = (balls90[i]);
cardContainer.appendChild(div);
}
}
getNumbers();
function getMore() {
var player1 = new Array();
balls90.sort(function() {
return [Math.floor(Math.random() * balls90.length)];
});
$("#press").click(function() {
$("#two").empty();
});
document.getElementById("press").addEventListener('click',getMore,true);
for (var i = 1; i <= 4; i++) {
var div = document.createElement("div");
div.style.height = (balls90[i]);
div.style.border = "thin solid black";
two.appendChild(div);
}
}
getMore();

would this work?
var balls90 = ['1px', '5px', '10px', '20px', '40px', '80px', '160px', '320px'];
var randomBalls90 = [];
var $cardContainer = $("#cardContainer");
var $two = $("#two");
$("#press").click(function() {
$("#cardContainer, #two").empty();
getNumbers();
});
function makedivs (el) {
for (var i = 1; i <= 4; i++) {
var $div = $("<div>");
$div.css({
height: randomBalls90[0],
border: "1px solid red"
});
$(el).append($div);
randomBalls90.splice(0, 1);
}
}
function getNumbers() {
balls90.sort(function() {
return [Math.floor(Math.random() * balls90.length)];
});
randomBalls90 = JSON.parse(JSON.stringify(balls90));
makedivs($cardContainer);
makedivs($two);
}
getNumbers();
Basically, I made making the random divs as a seperate function that accepts a element to append to.
When getNumbers is run, it clones the balls90 Array JSON.parse(JSON.stringify()) then loops through the array and on each loop, you remove the first object of the array so it's never repeated.

Related

making an div changes it background when mouse hover using JavaScript

Hello there i'm doing an course about JavaScript in the first exercise they ask to make a button that creates boxes,and in the second exercise they ask to use an function to when the mouse hover over the boxes they change color randomly, but i didn't manged to do it so here's firstly the box maker:
<body>
<button>CREATE</button>
<p>BOXES GENERATOR</p>
<div class="container"></div>
</body>
var button1 = document.querySelector("button");
button1.onclick = function() {
var cubeElement = document.createElement("div");
cubeElement.setAttribute("class", "bt");
var bodyElement = document.querySelector(".container");
bodyElement.appendChild(cubeElement);
var cubestyleElement = document.querySelectorAll(".bt");
for (var i = 0; i < cubestyleElement.length; i++) {
cubestyleElement[i].setAttribute(
"style",
"background: #850900; height: 100px; width: 100px; border: solid #000 2px;"
);
}
};
and there's the function to make it change colors randomly:
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
var newColor = getRandomColor(); // #E943F0
Here you go:
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
var i = 0;
var button1 = document.querySelector("button");
button1.onclick = function() {
var cubeElement = document.createElement("div");
cubeElement.setAttribute("class", "bt");
var bodyElement = document.querySelector(".container");
bodyElement.appendChild(cubeElement);
var cubestyleElement = document.querySelectorAll(".bt");
for (i; i < cubestyleElement.length; i++) {
var element = cubestyleElement[i];
element.setAttribute(
"style",
"background: #850900; height: 100px; width: 100px; border: solid #000 2px;"
);
element.onmouseover = function(){
var newColor = getRandomColor();
element.setAttribute(
"style",
"background:"+ newColor+"; height: 100px; width: 100px; border: solid #000 2px;"
);
}
}
};
<button>CREATE</button>
<p>BOXES GENERATOR</p>
<div class="container"></div>
Please check this.. Are you looking this?
var button1 = document.querySelector("button");
button1.onclick = function() {
var cubeElement = document.createElement("div");
cubeElement.setAttribute("class", "bt");
cubeElement.addEventListener('mouseover', function(event) {
event.target.style.backgroundColor = getRandomColor();
});
var bodyElement = document.querySelector(".container");
bodyElement.appendChild(cubeElement);
var cubestyleElement = document.querySelectorAll(".bt");
for (var i = 0; i < cubestyleElement.length; i++) {
cubestyleElement[i].setAttribute(
"style",
"background: #850900; height: 100px; width: 100px; border: solid #000 2px;"
);
}
};
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
<body>
<button>CREATE</button>
<p>BOXES GENERATOR</p>
<div class="container"></div>
</body>
Please let me know if you have any query.

Retrieve an element inside an object collection

I'm making board game, and I want that when I click in one of the places I turn them red. I have this array of divs, but I don't know how to retrieve the element given the number to turn it red. How can I do that, I'm trying to use .element but it's not working
var number = 3;
const board = [];
const boardWidth = boardHeight = 10;
(function() {
const boardElement = document.getElementById('board');
for (var y = 0; y < boardHeight; ++y) {
var row = [];
for (var x = 0; x < boardWidth; ++x) {
var cell = {};
cell.element = document.createElement('div');
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
painting();
})();
function painting() {
board[number][number].element.style.backgroundcolor = 'red';
}
#board {
width: calc(10 * 30px);
margin: auto;
}
#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
width: 30px;
height: 30px;
}
<div id="board"></div>
Your code look very confusing. board is an element and you are using it as an array.
Next come some code. I hope this is what you need:
let cellW = 100;
let cellH = 100;
function init(){
let boardArray = [];
let bStyle = window.getComputedStyle(board, null);
let bWidth = parseInt(bStyle.getPropertyValue("width"));
let bHeight = parseInt(bStyle.getPropertyValue("height"));
for (let y = 0; y < bHeight; y+=cellH) {
let row = [];
for (let x = 0; x < bWidth; x+=cellW) {
let cell = {};
cell.element = document.createElement('div');
cell.element.style.width = cellW +"px";
cell.element.style.height = cellH +"px";
board.appendChild(cell.element);
row.push(cell);
}
boardArray.push(row);
}
}
init();
let cells = Array.from(document.querySelectorAll("#board div"));
cells.map( cell => {
cell.addEventListener("click", e =>{
cell.style.background = "red"
})
})
#board{width: 1000px; height:500px; display:flex;flex-wrap:wrap;}
#board div{outline:1px solid;}
<div id="board"></div>
UPDATE:
I understand that you need to make the 4-th cell in the cells array red:
var number = 3;
const board = [];
const boardWidth = 10, boardHeight = 10;
function init() {
const boardElement = document.getElementById('board');
for (var y = 0; y < boardHeight; ++y) {
var row = [];
for (var x = 0; x < boardWidth; ++x) {
var cell = {};
cell.element = document.createElement('div');
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
board[number][number].element.style.background = "red"
}
window.addEventListener("load", init);
#board {
width: calc(10 * 30px);
margin: auto;
}
#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
width: 30px;
height: 30px;
}
<div id="board"></div>
I've addressed all of your issues but thought you might be interested in making things configurable. I reworked your code to make things config driven.
This will:
Take a config (or not) and merge it with a default config.
Build your board dynamically based on config values v. setting the dimensions via CSS
Allows for cell toggle (select/unselect) and matric position assignments
document.addEventListener('DOMContentLoaded', function(){
const extend = function(target, config, defaults){
defaults && extend(target, defaults);
if(target && config && typeof(config) === 'object'){
for(const i in config){
target[i] = config[i];
}
}
return target;
};
function Game(config){
const defaultConfig = {
boardElement: '#board',
// if a single digit is passed it will be duplicated for pos y 3 => 3,3
startPosition: 3,
cellSize: 30,
boardWidth: 10,
boardHeight: 10
};
// merge the default and user-defined config into a new config
this.config = extend({}, config || {}, defaultConfig);
// cache ref to your board element
this.boardElement = document.querySelector(this.config.boardElement);
// stores our collection of board items
this.board = [];
// draw the board
this.draw();
// set initial marker
if(this.config.startPosition){
if(this.config.startPosition instanceof Array){
this.paint.apply(this, this.config.startPosition);
}else{
this.paint(this.config.startPosition);
}
}
return this;
}
extend(Game.prototype, {
draw(){
for (let y = 0; y < this.config.boardHeight; ++y) {
const row = [];
for (var x = 0; x < this.config.boardWidth; ++x) {
const element = document.createElement('div');
const cell = {
element,
position: {
x: x + 1,
y: y + 1
}
};
// set cell width and height
element.style.height = element.style.width = `${this.config.cellSize}px`;
// handle selecting/unselecting cells
element.addEventListener('click', () => this.paint(cell.position.x, cell.position.y));
this.boardElement.appendChild(cell.element);
row.push(cell);
}
this.board.push(row);
}
// set board width and height
this.boardElement.style.width = `${this.config.boardWidth * this.config.cellSize}px`;
},
paint(x, y){
if(y === undefined){
y = x;
}
const element = this.board[y-1][x-1].element;
if(element){
const isSelcted = element.style.backgroundColor === 'red';
element.style.backgroundColor = isSelcted ? 'black' : 'red';
}
}
});
new Game({
startPosition: [5,4],
boardWidth: 8,
boardHeight: 8
});
});
#board {
margin: auto;
}
#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
}
<div id="board"></div>

Stop javascript "animation" onclick div

I'm a beginner in javascript and I'm trying to make a very simple game. I know that my code is not the best, but i want to make it working. I want to stop function nahoru() or make it move to the other way and after it touches the bottom of the page/100%, make it repeat.
<html>
<head>
<script>
function naloud() {
var elem = document.getElementById("krtek");
elem.style.top = '100%';
var eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
var elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}
var pos = 100;
var los = 0;
function nahoru() {
var elemend = document.getElementById("batn");
elemend.style.opacity = '0';
var elem = document.getElementById("krtek");
var id = setInterval(frame, 30);
function frame() {
if (pos == 0) {
clearInterval(id);
document.write('<center>GAME OVER<br>YOUR SCORE: ' + skore +
'<br>Press F5 for restart.')
} else {
pos = pos - 1;
elem.style.top = pos + '%';
}
}
}
var skore = 0;
function pric() {
skore++;
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
</script>
<style>
.prvni {
position: absolute;
width: 10%;
height: 110%;
left: 10%;
background-color: brown;
}
.druhy {
position: absolute;
width: 10%;
height: 110%;
left: 45%;
background-color: brown;
}
.treti {
position: absolute;
width: 10%;
height: 110%;
left: 80%;
background-color: brown;
}
</style>
</head>
<body onload="naloud()">
<button onclick="nahoru()" id="batn">START</button>
<div id="skore">Skore: 0</div>
<div id="krtek" class="prvni" onclick="pric()"></div>
<div id="krtek2" class="druhy" onclick="pric()"></div>
<div id="krtek3" class="treti" onclick="pric()"></div>
</body>
</html>
Declare id outside nahoru function,
like here
var pos = 100;
var los = 0;
var id = null;
Set interval in nahoru function,
like this (important, remove var from here)
id = setInterval(frame, 30);
Now clear interval in pric function
like this
function pric(elem) {
skore++;
clearInterval(id);
document.getElementById("skore").innerHTML = "Skore: " + skore;
elem.style.top = '+100%';
}
Working https://jsfiddle.net/ee1bdL5k/
You need declare this var outside from function, for the pric function:
var elem, eleme, elemen;
function naloud() {
elem = document.getElementById("krtek");
elem.style.top = '100%';
eleme = document.getElementById("krtek2");
eleme.style.top = '100%';
elemen = document.getElementById("krtek3");
elemen.style.top = '100%';
}

How to clone the contents of a div into another div with JavaScript?

I want to clone the images of the div leftSide into the div rightSide. On each click on the body the images on the left div should be cloned into the right div. But I can't get the result with the code I'm doing. Is there any mistake in my code? I want to use JavaScript.
Here's my code:
var theLeftSide = document.getElementById("leftSide");
var width = 500; var height = 500;
top_position = 0; var left_position = 0,
var numberOfFaces = 5;
var theRightSide = document.getElementById("rightSide");
var leftSideImages = theLeftSide.cloneNode(true);
document.getElementById("rightSide").appendChild(leftSideImages);
for (var i = 0; i < 5; i++) {
createElement(i);
numberOfFaces += 5;
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
top_position = Math.random() * 500 ;
left_position = Math.random() * 500 ;
Here is a simple example that clones an HTMLElement in vanilla javascript:
additional information can be found in MDN
function CloneCtrl() {
'use strict';
var self = this;
self.source = document.querySelector('.source');
self.target = document.querySelector('.target');
self.cloneSource = function(event) {
var clone = self.source.cloneNode(true);
self.target.appendChild(clone);
}
document
.getElementById('cloneBtn')
.addEventListener('click', self.cloneSource)
;
}
document.addEventListener('DOMContentLoaded', CloneCtrl);
.source {
background: lightseagreen;
width: 100px;
height: 100px;
line-height: 100px;
overflow: hidden;
margin: 5px;
display: inline-block;
text-align: center;
color: #fff;
}
.target {
border: 1px solid lightcoral;
min-height: 110px;
}
<div><button id="cloneBtn">Clone Source</button></div>
<div class="source">SOURCE</div>
<hr>
<div class="target"></div>
With jQuery, you can do it kike that:
$('#div2').html($('#div1').html());
which is found from this question: Copy the content of a div into another div.
You don't actually provide many details, thus the best I can post, hope it helps!!
you could simply try this if you have second div on page.
document.getElementById("SecondDv").innerHTML = document.getElementById("FirstDv").innerHTML;
This will copy whatever is there in FirstDiv to Second. lmk if it works.

Random color on different div's

I have 3 div's
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<button>Enter</button>
I want to give it a random color using javascript controlled css.
Like this:
var randomColor = Math.ceil(Math.random() * 3);
var color = "";
//Accessing the divs
var box1 = document.querySelector("#box1");
var box2 = document.querySelector("#box2");
var box3 = document.querySelector("#box3");
//Event
var button = document.querySelector("button");
button.addEventListener("click", randomize, false);
button.style.cursor = "pointer";
function render(){
box1.style.background = color;
box2.style.background = color;
box3.style.background = color;
}
function randomize(randomColor){
switch(randomColor){
case 1:
color = "red";
break;
case 2:
color = "blue";
break;
case 3:
color = "green";
break;
}
render();
}
The problem is that, it's giving me the same color in every div.
Any idea how can i solve this, I want to do it pure javascript and css no jquery if possible. Im still learning javascript. Thank you..
You could use classes instead of ids and simplify your code to following.
// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");
var button = document.querySelector("button");
button.addEventListener("click", function () {
for (i = 0; i < boxes.length; i++) {
// Pick a random color from the array 'colors'.
boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
boxes[i].style.width = '100px';
boxes[i].style.height = '100px';
boxes[i].style.display = 'inline-block';
}
});
button.style.cursor = "pointer";
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button>Enter</button>
Randomizing the colors on page refresh/load.
// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");
for (i = 0; i < boxes.length; i++) {
// Pick a random color from the array 'colors'.
boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
boxes[i].style.width = '100px';
boxes[i].style.height = '100px';
boxes[i].style.display = 'inline-block';
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
How about this?
http://jsfiddle.net/stackmanoz/vymmb10s/
CSS-
div[class^="box"]{
width:100px;
height:100px;
border:1px solid;
display:inline-block;
}
jQuery-
var colors = ['red', 'blue', 'green', 'gray', 'black', 'yellow'];
$(function(){
$("#btn").click(function() {
$('div[class^="box"]').each(function(){
var randomColor = Math.floor(Math.random() * colors.length)
$(this).css('background-color', colors[randomColor])
});
});
});
var r = Math.floor(Math.random()*255);
var g = Math.floor(Math.random()*255);
var b = Math.floor(Math.random()*255);
for (var i = 0; i <= 5; i++) {
var div = document.getElementsByClassName("div")[i].style.backgroundColor = "rgb("+r+","+g+","+b+")";
}
div {
width: 200px;
height:200px;
display: inline;
float: left;
margin: 15px;
background-color: red;
}
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
*
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
position: relative;
border: 1px solid black;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
</body>
<script>
let colors = ['red', 'green', 'blue', 'yellow'];
(function () {
document.getElementById("first").style.backgroundColor = assignColor();
document.getElementById("second").style.backgroundColor = assignColor();
document.getElementById("third").style.backgroundColor = assignColor();
document.getElementById("fourth").style.backgroundColor = assignColor();
})();
function assignColor() {
let colorIndex = Math.floor(Math.random() * colors.length);
let color = colors[colorIndex];
colors.splice(colorIndex, 1);
return color;
}
</script>
</html>
I was appalled by the list of named string colors and didn't see anyone using hex. For anyone like me that wanted something different, here you go:
function randomInt(max=1, min=0){
// scale random number from 0 to 1 to desired min and max
return parseInt( Math.random() * (max - min) + min );
}
function twoPlaces(sNum=''){
// make sure all strings have a length greater than 1
// eg: "f" => "0f"
return sNum.length > 1 ? sNum : twoPlaces('0'+sNum);
}
function randomColor(){
// make each color's hex string
let r = twoPlaces( randomInt(255,0).toString(16) );
let g = twoPlaces( randomInt(255,0).toString(16) );
let b = twoPlaces( randomInt(255,0).toString(16) );
// return hex color string
return `#${r}${g}${b}`;
}
function updateColors(){
// loop through all elements with class "random"
document.querySelectorAll(".random").forEach( (el)=>{
// set each element/'s color to a random hex
el.setAttribute("style",`background-color:${ randomColor() }`);
} );
}
// add function to randomizer
let randomizer = document.querySelector("#colorRandomizer");
randomizer.addEventListener("click",updateColors);
// initialize colors
randomizer.dispatchEvent( new Event("click") );
div {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.random{
height: 100px;
}
<button id="colorRandomizer">Randomize</button>
<div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
<div class="random"></div>
</div>

Categories