random dots
by Alexandru Gatea
HTML
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div class="container">
<button class="generate">Add dot</button>
<div class="box">
</div>
</div>
CSS
* {
margin: 0;
padding: 0;
}
.container {
position: relative;
width: 100%;
height: 100vh;
background: #eee;
}
.box {
width: 300px;
height: 300px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #444;
overflow: hidden;
font-size: 0;
}
.circle {
display: inline-block;
width: 30px;
height: 30px;
border-radius: 50%;
background: #ff8800;
position: absolute;
}
button {
border: none;
background: #ff8800;
padding: 5px 15px;
color: #fff;
margin: 10px;
cursor: pointer;
outline: none;
}
button:active {
background: #ff5500;
}
JavaScript
jQuery(document).ready(function($) {
var generate = $('.generate');
generate.on('click', function() {
dot();
});
function dot() {
var d = document.createElement('div');
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
var boxHeight = $('.box').height(),
boxWidth = $('.box').width(),
$div = $('.circle'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = boxHeight - divHeight,
widthMax = boxWidth - divWidth;
$(d).addClass("circle").appendTo($(".box")).css({
left: Math.floor(Math.random() * widthMax),
top: Math.floor(Math.random() * heightMax),
background: color
});
}
});