making an div changes it background when mouse hover using JavaScript - 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.

Related

How to create containers all at the same time with random colours?

my following code essentially creates a number of boxes according to the input of the user.
However i want to ensure that when they are created, they all have a random colour.
I also want to ensure that for each new box created, it sets the margin-left of the box to be double the previous box’s margin (where the first box has margin-left 5px).
I have no idea how to do this!
function getNewRandomColor()
{
var myArray = ['red', 'green', 'blue'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("container").style.backgroundColor = rand;
}
var empty = true;
function setup()
{
if (!empty)
{
remove();
}
size = document.getElementById("input").value
var container = document.getElementById("container");
// create boxes
for (var i = 0; i < size; i++)
{
// Create a box
var box = document.createElement("div");
// insert number
box.innerHTML = i+1;
// Add into the document
container.appendChild(box);
empty = false;
}
}
function remove()
{
// Get all the generated boxes
var boxes = document.getElementById("container").children;
// Iterate through all boxes
for (var x = 0; x < boxes.length;)
{
var bA = boxes[x];
bA.remove();
}
}
body {
font-family:sans-serif;
font-weight:700;
font-size:15pt;
}
#container div, div.selected {
width: 2em;
height: 1.5em;
float: left;
padding: 1em;
margin: 1vw;
padding-top:1.5em;
text-align: center;
transition: background 1s;
}
div, .unselected {
background: #a0aeef;
}
<input type="number" name="input" id="input">
<button onclick="setup();">Draw</button>
<button onclick="remove();">Remove</button>
<div id="container"></div>
You could only retrieve the array key and use it as a classname, style on the fly can be applied once the element is part of the dom of the document :
ex
function getNewRandomColor(e)
{
var myArray = ['red', 'green', 'blue'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
return rand;
}
var empty = true;
function setup()
{
if (!empty)
{
remove();
}
size = document.getElementById("input").value
var container = document.getElementById("container");
// create boxes
for (var i = 0; i < size; i++)
{
// Create a box
var box = document.createElement("div");
var rdmClass= getNewRandomColor();
box.setAttribute("class",rdmClass);
marginVar = 10*i;
box.setAttribute("style","--margR:" + marginVar + ";border:solid/* here you bg with hex value to be updated " );
// insert number
box.innerHTML = i+1;
// Add into the document
container.appendChild(box);
empty = false;
}
}
function remove()
{
// Get all the generated boxes
var boxes = document.getElementById("container").children;
// Iterate through all boxes
for (var x = 0; x < boxes.length;)
{
var bA = boxes[x];
bA.remove();
}
}
body {
font-family:sans-serif;
font-weight:700;
font-size:15pt;
}
#container div, div.selected {
width: 2em;
height: 1.5em;
float: left;
padding: 1em;
margin: 1vw;
padding-top:1.5em;
text-align: center;
transition: background 1s;
}
div, .unselected {
background: #a0aeef;
}
#container div{
margin-right:calc(var(--margR)*1px); /* updated from the style attribute added from js loop */
}
.red {background:red;}
.green {background:green;}
.blue {background:blue;}
<input type="number" name="input" id="input">
<button onclick="setup();">Draw</button>
<button onclick="remove();">Remove</button>
<div id="container"></div>

Clicking div does not change the width and height

I made a clicking div. After clicking the div (some_id1, someenter code here_id2), you need to change the value on each div (width, height, background-color).
Background-color works normally, but width and height are not working. I cannot find out where I made a mistake.
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
};
}
function ColorChange(){
if(clickedDivId == "some_id1"){
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
if(clickedDivId == "some_id2"){
var y = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = y;
}
}
function ChengeWidth(){
if(clickedDivId == "some_id1"){
var z = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = z;
}
if(clickedDivId == "some_id2"){
var w = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = w;
}
}
#some_id1{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
#some_id2{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
<select id="divwidth" onchange="ChengeWidth()">
<option value="100px">100px</option>
</select>
<input type="color" id="divbackgroundcolor" onchange="ColorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
};
}
function ColorChange(){
if(clickedDivId == "some_id1"){
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
if(clickedDivId == "some_id2"){
var y = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = y;
}
}
function ChengeWidth(){
if(clickedDivId == "some_id1"){
var z = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = z;
}
if(clickedDivId == "some_id2"){
var w = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = w;
}
}
#some_id1{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
#some_id2{
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<select id="divwidth" onchange="ChengeWidth()">
<option value="100px">100px</option>
<option value="200px">200px</option>
<option value="300px">300px</option>
<option value="50px">50px</option>
</select>
<input type="color" id="divbackgroundcolor" onchange="ColorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>
</body>
</html>
The menu only has one option, so you can't change the value and the onchange event never triggers. If you give it multiple options, the code works.
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
};
}
function ColorChange() {
if (clickedDivId == "some_id1") {
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
if (clickedDivId == "some_id2") {
var y = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = y;
}
}
function ChengeWidth() {
if (clickedDivId == "some_id1") {
var z = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = z;
}
if (clickedDivId == "some_id2") {
var w = document.getElementById("divwidth").value;
document.getElementById(clickedDivId).style.width = w;
}
}
#some_id1 {
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
#some_id2 {
width: 50px;
height: 50px;
margin: 10px;
background-color: red;
}
<select id="divwidth" onchange="ChengeWidth()">
<option value="50px">50px</option>
<option value="100px">100px</option>
<option value="150px">150px</option>
<option value="200px">200px</option>
</select>
<input type="color" id="divbackgroundcolor" onchange="ColorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>
HTML
<div id="some_id1" class="clickable"></div>
<div id="some_id2" class="clickable"></div>
CSS
.clickable {
width: 50px;
height: 50px;
margin: 10px;
}
Javascript
let current;
function changeColor() {
const color = document.getElementById("divbackgroundcolor").value;
current.style.backgroundColor = color;
}
function changeWidth() {
const width = document.getElementById("divwidth").value;
current.style.width = width;
}
function initialize() {
const clickable = document.querySelectorAll('.clickable');
clickable.forEach((item) => {
item.onClick = () => {
current = this;
changeColor();
changeWidth();
}
});
}
initialize();
My approach would be to split the problem in small chunks as you can see in my javascript proposal. Basically each method is a step which can be fully tested before moving on to the next portion:
Add event handlers to elements (I changed it to a class, rather than applying it to all <div>-elements). Use console.log to make sure everything works as expected.
Change the color; first call it immediately without the click handling in between. Does it work? Probably not because I did not include #divwidth in my example, but hopefully you see the approach I'm aiming for.
Next change the width; same as previous: I did not include #divbackgroundcolor so it won't work yet
Finally tie everything together and call the methods within the click handler
Hopefully I've pointed you in the right direction; good luck!

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>

Dom html javascript about onclick

I want to generate five image imgs first in left side, then remove the lastchild of it and copy the rest to the right side. If user clicks the extra img in left side, then clear all and generate more 5(10) img in left and copy 9 to the right side, and so on. If user clicks the wrong place, alert ("game over").Here is my code:
<html>
<head>
<style>
img{
position: absolute;
}
div{
position: absolute;
width: 500px;
height: 500px;
}
#rightSide { left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberOfFaces = 5;
function generateFaces(){
var theLeftSide = document.getElementById("leftSide");
for (var i = 0; i < numberOfFaces; i++){
var img = document.createElement("img");
img.src = "smile.png";
var randomTop = Math.random() * 400;
var randomLeft = Math.random() * 400;
img.style.top = randomTop + "px";
img.style.left = randomLeft + "px";
theLeftSide.appendChild(img);
}
var theRightSide = document.getElementById("rightSide");
leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightSide").appendChild(leftSideImages);
var theBody = document.getElementByTagName("body")[0];
theLeftSide.lastChild.onclick = function nextLevel(event){
event.stopPropagation();
while (theBody.firstChild){
theBody.removeChild(theBody.firstChild);
}
numberOfFaces += 5;
generateFaces();
}
theBody.onclick = function gameover(){
alert("Game Over");
thBody.onclick = null;
theLeftSide.lastChild.onclick = null;
}
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>click on the extra smiling face on the left</p>
<div id = "leftSide">
</div>
<div id = "rightSide">
</div>
</body>
</html>
I could generate and clone at first time, but when I click, nothing happens, so what is the problem?
This may be a typing error.
var theBody = document.getElementsByTagName("body")[0];
your code: var theBody = document.getElementByTagName("body")[0];
I suggest to use a good editor for html. I fixed the error with Jetbrain phpStorm but better ones may exist.
Bellow is a modified version that worked for me. Notice that in this version I added the events on all children instead of the whole document body. I don't know but for me it feels more accurate not to end the game on a user clicks on a white space for example.
<html>
<head>
<style>
img{
position: absolute;
}
div{
position: absolute;
width: 500px;
height: 500px;
}
#rightSide { left: 500px;
border-left: 1px solid black;
}
</style>
<script>
var numberOfFaces = 5;
var theBody;
var theLeftSide;
var theRightSide;
function generateFaces(){
theBody = document.getElementsByTagName("body")[0];
theLeftSide = document.getElementById("leftSide");
theRightSide = document.getElementById("rightSide");
for (var i = 0; i < numberOfFaces; i++){
var img = document.createElement("img");
img.src = "smile.png";
var randomTop = Math.random() * 400;
var randomLeft = Math.random() * 400;
img.style.top = randomTop + "px";
img.style.left = randomLeft + "px";
if(theLeftSide != null)
theLeftSide.appendChild(img);
else
{
alert("Game Over");
return;
}
}
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
document.getElementById("rightSide").appendChild(leftSideImages);
addEvents();
}
function addEvents(){
for(var i=0; i < theLeftSide.childNodes.length; i++){
theLeftSide.childNodes[i].onclick = nextLevel;
}
}
function removeEvents(){
for(var i=0; i < theLeftSide.childNodes.length; i++){
theLeftSide.childNodes[i].onclick = null;
}
}
function nextLevel(event){
if(this == theLeftSide.lastChild){
event.stopPropagation();
theLeftSide.innerHTML = "";
theRightSide.innerHTML = "";
numberOfFaces += 5;
generateFaces();
}
else
{
alert("Game Over");
removeEvents();
}
}
window.onload = generateFaces;
</script>
</head>
<body>
<h1>Matching Game</h1>
<p>click on the extra smiling face on the left</p>
<div id = "leftSide">
</div>
<div id = "rightSide">
</div>
</body>
</html>

Unique Array Values across Two Functions and Two Divs

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.

Categories