Calling a javascript function infinitly on click of a button? - javascript

Okay so this is a bit of a weird request. So I've programmed tiles that generate using JavaScript (with the help of people here on stack overflow) now I would like to make it so that on the click of a button my changecolors function is called a set number of times so that the colors of the tiles randomly change before your eyes. I've got a button that every time you click it the colors change, but how can I make it so on that click they continuously change? I've tried using the JavaScript function set Interval(function, time) and couldn't seem to get it to work. Just in case, I will also inform you that I am putting a button in that will also stop the random color changes.. Here's the code. Any help would be great!!
<!doctype html>
<html>
<style>
.cell {
width: 100px;
height: 100px;
display: inline-block;
margin: 1px;
padding:4px;
}
button{
float:left;
padding:4px;
}
</style>
<title></title>
<head><script type="text/javascript">
function generateGrid(){
for (i = 0; i < 5; i++) {
for (b = 0; b < 5; b++) {
div = document.createElement("div");
div.id = "box" + i +""+ b;
div.className = "cell";
document.body.appendChild(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors(){
for(i =0;i < 5; i++){
for (b=0;b<5;b++){
var holder=document.createElement("div");
holder=document.getElementById("box" + i +""+ b);
holder.style.backgroundColor = getRandomColor();
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</head>
<body>
<script>
generateGrid();
changeColors();
</script>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="window.setInterval(changeColors(),2000);">Click me to start cycle</button>
</body>
</html>

Your changeColors() should have been changeColors for window.setInterval.
I cleaned up your code and added the stop/start buttons. By creating an array of elements, it saves the changeColors function having to locate each element every iteration. Lastly I changed your generateGrid function to accept a width and height. A bit overkill but I got carried away :)
HTML
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="startCycle();">Start cycle</button>
<button onclick="stopCycle();">Stop cycle</button>
<br>
<br>
JavaScript
var elements = [];
function generateGrid(width, height) {
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var div = document.createElement("div");
div.id = "box" + y + "" + x;
div.className = "cell";
document.body.appendChild(div);
elements.push(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors() {
for (e in elements) {
elements[e].style.backgroundColor = getRandomColor();
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var interval = null;
function startCycle() {
if (interval) return;
interval = window.setInterval(changeColors, 500);
}
function stopCycle() {
clearInterval(interval);
interval = null;
}
generateGrid(3, 5);
changeColors();
Demo

Simple Just added one function on Click of button try this:
<style>
.cell {
width: 100px;
height: 100px;
display: inline-block;
margin: 1px;
padding:4px;
}
button{
float:left;
padding:4px;
}
</style>
<title></title>
<head><script type="text/javascript">
function generateGrid(){
for (i = 0; i < 5; i++) {
for (b = 0; b < 5; b++) {
div = document.createElement("div");
div.id = "box" + i +""+ b;
div.className = "cell";
document.body.appendChild(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors(){
for(i =0;i < 5; i++){
for (b=0;b<5;b++){
// var holder=document.createElement("div");
var holder=document.getElementById("box" + i +""+ b);
holder.style.backgroundColor = getRandomColor();
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</head>
<body>
<script>
generateGrid();
changeColors();
function animate1()
{
setInterval(function(){
changeColors();
},5000);
}
</script>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="animate1();">Click me to start cycle</button>
</body>
Note: setTimeout function gets called only once after your set duration where setTimeout gets called indefinite unless you use clearInterval() to Stop it.

Your setTimeoutFunction was not sintatically correct
var stop = false;
function generateGrid(){
for (i = 0; i < 5; i++) {
for (b = 0; b < 5; b++) {
div = document.createElement("div");
div.id = "box" + i +""+ b;
div.className = "cell";
document.body.appendChild(div);
}
document.body.appendChild(document.createElement("br"));
}
}
function changeColors(){
for(i =0;i < 5; i++){
for (b=0;b<5;b++){
var holder=document.createElement("div");
holder=document.getElementById("box" + i +""+ b);
holder.style.backgroundColor = getRandomColor();
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
document.addEventListener("DOMContentLoaded", function(event) {
generateGrid();
changeColors();
});
.cell {
width: 100px;
height: 100px;
display: inline-block;
margin: 1px;
padding:4px;
}
button{
float:left;
padding:4px;
}
<!doctype html>
<html>
<title></title>
<body>
<button onclick="changeColors();">Click me to change colors</button>
<button onclick="window.setInterval(function(){changeColors();},2000);">Click me to start cycle</button>
</body>
</html>
Edited to work without jQuery

Related

Colored Squares HTML/Javascript

Here is the current index (HTML and JavaScript):
var maxZ = 1000;
window.onload = function() {
var add = document.getElementById("add");
add.onclick = addSquare;
var colors = document.getElementById("colors");
colors.onclick = changeColors;
var squareCount = parseInt(Math.random() * 21) + 30;
for (var i = 0; i < squareCount; i++) {
addSquare();
}
}
//Generates color
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function addSquare() {
var square = document.createElement("div");
var squareArea = document.getElementById("squareArea");
square.className = "square";
square.style.left = parseInt(Math.random() * 650) + "px";
square.style.top = parseInt(Math.random() * 250) + "px";
square.style.backgroundColor = getRandomColor();
square.onclick = squareClick;
squareArea.appendChild(square);
}
function changeColors() {
var squares = document.querySelectorAll("#squareArea div");
for (i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = getRandomColor();
}
}
function squareClick() {
var oldZ = parseInt(this.style.zIndex);
if (oldZ == maxZ) {
this.parentNode.removeChild(this);
} else {
maxZ++;
this.style.zIndex = maxZ;
}
}
<html>
<head>
<title>Colored Squares</title>
<script src="Squares.js" type="text/javascript"></script>
<link href="Squares.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="squareArea"></div>
<div>
<button id="add">Add Square</button>
<button id="colors">Change Color</button>
</div>
<p>Click a square to move it to the front.</p>
</body>
</html>
Here is the goal:
Edit Colored squares to add the following functionality.
Users will be able to click a square and drag it to any position on the screen. - When the user lets go of the click it will stay in that position.
In order to accomplish this you will need to add Prototype and Scriptaculous to the scripts loaded in the html and use their functionality.
You will also need to create 3 functions in the JavaScript file:
function squareMouseMove(event)
function squareMouseDown(event)
function squareMouseUp(event)
Add appropriate global variables
Change the creation of the squares to added observers for the mouse events that execute the functions.
The issue that you have with your code is that the squares are empty, so they collapse to nothing and you will not see them. Add a width and height to them so you can see them.
Another issue is that you're specifying the left and right, but these properties will have no effect unless you make them absolutely positioned.
Here is your code working with the width, height, and position properties added:
var maxZ = 1000;
window.onload = function() {
var add = document.getElementById("add");
add.onclick = addSquare;
var colors = document.getElementById("colors");
colors.onclick = changeColors;
var squareCount = parseInt(Math.random() * 21) + 30;
for (var i = 0; i < squareCount; i++) {
addSquare();
}
}
//Generates color
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function addSquare() {
var square = document.createElement("div");
var squareArea = document.getElementById("squareArea");
square.className = "square";
square.style.left = parseInt(Math.random() * 650) + "px";
square.style.top = parseInt(Math.random() * 250) + "px";
square.style.width = "100px";
square.style.height = "100px";
square.style.position = "absolute";
square.style.backgroundColor = getRandomColor();
square.onclick = squareClick;
squareArea.appendChild(square);
}
function changeColors() {
var squares = document.querySelectorAll("#squareArea div");
for (i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = getRandomColor();
}
}
function squareClick() {
var oldZ = parseInt(this.style.zIndex);
if (oldZ == maxZ) {
this.parentNode.removeChild(this);
} else {
maxZ++;
this.style.zIndex = maxZ;
}
}
<html>
<head>
<title>Colored Squares</title>
<script src="Squares.js" type="text/javascript"></script>
<link href="Squares.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="squareArea"></div>
<div>
<button id="add">Add Square</button>
<button id="colors">Change Color</button>
</div>
<p>Click a square to move it to the front.</p>
</body>
</html>

Inline style edited with JavaScript is being ignored

I'm trying to use document.getElementByClassId().style.color to change the color of an element in my HTML document. I can see that it does add an inline style tag to the element but they are seemingly ignored by the browser.
I tried using the !important tag but that changed nothing. Here is my HTML document. I changed my CSS for the elements I want to modify into inline tags but they are ignored as well. Everything else works so far.
Here is my code (I'm a beginner please go easy on me :/).
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel">';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.color = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
You have to style the backgroundColor instead of color, because the cells don't contain any text, to which the color would be applied to
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel"></td>';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.backgroundColor = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>

Display single image multiple times in a table using JS

I have to make a game in which there is an 8x8 table and a coin displays on them(more than at 10 positions at a time) for 3000milliseconds on different position simultaneously. The coin display should start at a click of "Start" button and it continues for 1minute. My problem is that I am not able to make a random function which generates images randomly on different positions.it is giving some error of appendchild undefined.I want my image to display randomly on different positions),Here what I've tried so far.I've just started learning JS so please don't judge my code & i'm posting this again because i didn't get any response in my previous post.
I had "display:none;" all the coins and i want a random function at multiple positions on which the coins displays block.
PS:I can't use any Jquery and remove the mistakes done previously
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
var tr = tbl.getElementsByTagName("tr")[randomNumber];
var td = tbl.getElementsByTagName("td")[randomNumber];
var img = tbl.getElementById("coin_image");
td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
i don't know exactly what you are looking for but it may works using same id multiple times is not a good choice
<script type="text/javascript">
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image'+i+'">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
//var tr = tbl.getElementsByTagName("tr")[randomNumber];
//var td = tbl.getElementsByTagName("td")[randomNumber];
var img = document.getElementById("coin_image"+randomNumber+"");
//td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
I think I could tweak your code:
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.id = 'myTable';
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="http://icons.iconarchive.com/icons/awicons/vista-artistic/128/coin-icon.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.getElementById('myTable');
var randomNumber = Math.floor(Math.random() * 7);
var tr = Array.prototype.slice.call(tbl.getElementsByTagName("tr"))[randomNumber];
var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
var img = document.getElementById("coin_image");
td.appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
Your inaccuracies:
add an id to the table when you initially create it in function tableCreate() like tbl.id ='myTable';
variable tbl in onTimer() function shoudn't contain a new table but
rather the existing one like var tbl = document.getElementById('myTable');
functions like getElementsByTagName("tr") return HTMLCollections,
not arrays. To convert it into array use
Array.prototype.slice.call(tbl.getElementsByTagName("tr"))
If I am not mistaken, you can call getElementById only on
document, so it should be var img = document.getElementById("coin_image");, not var img =tbl.getElementById("coin_image");
td variable in onTimer's interval already contains the td
element, no need to add an index. So, it should be
td.appendChild(img);
In order to avoid placing all the coins in the same row, change var
td = Array.prototype.slice.call(tbl.getElementsByTagName("td"))[randomNumber];
to var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
It makes your code work, but there are some other, lets say, logical problems because the coins do not disappear from the cells. Also they only appear on cells with coordinates like (0,0) (2,2) (4,4) etc. because you generate the random number only once and then use it for both - row and column. I don't know maybe it is what you want. If not, work on it too.

How to populate browser's entire window/document with rectangles

I want to populate the entire window with rectangles, no matter what size of window it is. eg. If rectangles are 250px wide, and window is 1000px wide, then it shold be 4 rec. in one row. I managed to fill just one row. Here is the code below
<!DOCTYPE HTML>
<html>
<head>
<style>
div {
width: 250px;
height: 150px;
border: 1px solid black;
border-collapse: collapse;
display: block;
position: fixed;
}
</style>
<script>
function ubaci_div() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}
</script>
</head>
<body id="body">
<p id="p" onclick="ubaci_div()">Klikni</p>
</body>
</html>
I think you are asking for something like this?
https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/9/
function ubaci_div() {
var i = 0;
var h = window.innerHeight;
var num = (h / 150);
for (i = 0; i < num; i++) {
alert(num);
loop();
var br = document.createElement('br');
}
}
function loop() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth - 250; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}
Something like this?
JSFiddle: https://jsfiddle.net/vc7w608m/
var rectangleWidth = 250;
var rectangleHeight = 100;
var columnCount = Math.ceil(window.innerWidth / rectangleWidth);
var rowCount = Math.ceil(window.innerHeight / rectangleHeight);
console.log(columnCount, rowCount)
for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
var rowDiv = document.createElement("div");
rowDiv.style.height = rectangleHeight + "px";
rowDiv.style["white-space"] = "nowrap";
rowDiv.style["overflow"] = "hidden";
document.body.appendChild(rowDiv);
for (var columnIndex = 0; columnIndex < columnCount; columnIndex++) {
var rectangle = document.createElement("div");
rectangle.style.height = rectangleHeight + "px";
rectangle.style.width = rectangleWidth + "px";
rectangle.style.display = "inline-block";
rectangle.style["background-color"] = "rgb(" + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ")";
rowDiv.appendChild(rectangle);
}
}

Getting random value with javascript

Guys i am trying to get random values when click a button and made that code but when i click somehow one value repeat itself 4 times like "k0k2k4k6" , "n0n2n4n6".
Why this happenning?Cos its not a coincidence.
Thanks in advance! JSFIDDLE
$(function() {
var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
var word = words[Math.floor(Math.random() * words.length)];
var myLength = 8;
function random() {
for (var i = 0; i < myLength; i++) {
$('#content').append(word + i++);
}
}
$('#button').click(function() {
random();
});
});
#content {
width: 200px;
height: 50px;
border: 1px solid #333;
margin-top: 50px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click</button>
<div id="content"></div>
Why is it generating 4 times?
Because your maximum limit is 8 and you are incrementing twice, one in the for loop and inside there.
Moving the word (generated dynamically) definition inside the loop solves it:
$(function() {
var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
var myLength = 8;
function random() {
// Also I would clear before generating new:
$('#content').html("");
for (var i = 0; i < myLength; i++) {
var word = words[Math.floor(Math.random() * words.length)];
$('#content').append(word + i++);
}
}
$('#button').click(function() {
random();
});
});
#content {
width: 200px;
height: 50px;
border: 1px solid #333;
margin-top: 50px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click</button>
<div id="content"></div>
Move your variables into the function:
$(function() {
function random() {
var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
var word = words[Math.floor(Math.random() * words.length)];
var myLength = 8;
for (var i = 0; i < myLength; i++) {
$('#content').append(word + i++);
}
}
$('#button').click(function() {
random();
});
});
Try this
$(function() {
var words = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
var myLength = 8;
function random() {
var word = words[Math.floor(Math.random() * words.length)];
for (var i = 0; i < myLength; i++) {
$('#content').append(word + i++);
}
}
$('#button').click(function() {
$('#content').html('');
random();
});
});

Categories

Resources