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();
});
});
Related
I'm trying to build a visual representation of some famous sorting algorithms in javascript, but I can't understand why my code doesn't print each iteration even if the print function is in the for loop. I only get the final result.
This is the sorting function, in particular the selection sort algorithm:
function selectionSort(array) {
var i, j, min_idx;
let n = array.length;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i + 1; j < n; j++)
{
if (array[j] < array[min_idx])
{
min_idx = j;
}
}
var temp = array[min_idx];
array[min_idx] = array[i];
array[i] = temp;
printArray(array);
}
}
And this is the printing function:
function printArray(array) {
document.getElementById('container').innerHTML ='';
for(let i = 0; i < array.length; i++)
{
document.getElementById('container').innerHTML += '<div class = "column '+i+'" id = "'+i+'" style = "height: '+array[i]+'px;"></div>';
}
}
Thank you a lot
It's what #Bravo states in the comments. The screen is updates at least 60 times per second, but it takes less time to do the sorting. So you need to add a timeout in a recursive loop so you can actually see the animation.
I replaced the first for loop with this recursive loop. I think the code it self-explanatory.
I did some optimization in your printArray(), where it takes time to constantly doing DOM changes. Instead, loop through to create a text string and then add it once to #container.innerHTML. There were also some faulty thinking in the value that you gave the visualized divs, where you only added the order (i), instead of adding the actual value (array[i]).
const iterationLegend = document.getElementById('iterations');
const containerDiv = document.getElementById('container');
const ANIMATION_SPEED = 1000;
const RESTART = 0;
var firstIteration;
function startSelectionSort(array) {
firstIteration = RESTART;
selectionSort(array);
}
function selectionSort(array) {
let min_idx = firstIteration,
n = array.length;
for (let j = firstIteration + 1; j < n; j++) {
if (array[j] < array[min_idx]) {
min_idx = j;
}
}
var temp = array[min_idx];
array[min_idx] = array[firstIteration];
array[firstIteration] = temp;
visualizeArray(array);
iterationLegend.textContent = 'iteration ' + firstIteration;
if (firstIteration < n - 1) {
firstIteration++;
setTimeout(selectionSort.bind(this, array), ANIMATION_SPEED);
} else {
iterationLegend.textContent = 'Done';
}
}
function visualizeArray(array) {
let elementStr = '';
let value = 0;
for (let i = 0; i < array.length; i++) {
value = array[i];
elementStr += `<div class="column${value}" data-value="${value}"></div>`;
}
containerDiv.innerHTML = elementStr;
}
startSelectionSort([2, 3, 5, 5, 1, 1, 1, 1, 4]);
fieldset {
display: inline;
}
#iterations {
font-size: 13px;
text-transform: uppercase;
}
#container {
display: inline-flex;
}
#container > div {
width: 10px;
height: 100px;
margin: 2px 1px 0px;
}
.column1 {
background-color: brown;
}
.column2 {
background-color: black;
}
.column3 {
background-color: teal;
}
.column4 {
background-color: red;
}
.column5 {
background-color: indigo;
}
<fieldset>
<legend id="iterations">Iterations</legend>
<div id="container"></div>
</fieldset>
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>
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
I am trying to make a grid in an HTML using plain Javascript. I have a URL in which number is given and basis on that I am generating a grid.
My url is like this abc.html?num=5 and basis on this num=5 I need to generate a grid of 5x5 size.
Currently I am using jQuery but I want to see how we can do the same thing with plain Javascript. Here is my jsfiddle example.
Below is my full content of abc.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var defaultNum = 4;
var url = window.location.search;
var num = parseInt(url.split('num=')[1]) || defaultNum;
var container = $('#container');
var width = container.outerWidth();
createGrid(num);
function createGrid(n) {
if (!$.isNumeric(n) || n <= 0) return;
for (var i = 0; i < n * n; i++) {
var dimension = width / n;
var cell = $('<div/>').addClass('gridCell').css({
'width': dimension + 'px',
'height': dimension + 'px'
});
container.append(cell);
}
}
});
</script>
<style>
#container {
width: 300px;
height: 300px;
}
#container > .gridCell {
float: left;
padding: 0;
margin: 0;
border: 0;
outline: 1px solid;
}
</style>
</head>
<body>
<div id="container"></div>
</body>
</html>
How can I do the same thing with plain Javascript instead of using any libraries like jquery which I am using currently?
This can't be demonstrated in a jsfiddle because it requires access to the url. But here is the code, put it in an HTML and test it out:
<html>
<style>
#container {
width: 300px;
height: 300px;
}
#container > .gridCell {
float: left;
padding: 0;
margin: 0;
border: 0;
outline: 1px solid;
}
</style>
<body>
<div id="container">
</div>
<script>
// QueryString is the function that gets the num parameter.
// Source to this function: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
} ();
var defaultNum = 3;
var num = parseInt(QueryString.num) || defaultNum;
var container = document.getElementById('container');
var width = container.offsetWidth;
createGrid(num);
function createGrid(n) {
// If n is not a number or smaller than 0
if(isNaN(n) || n <= 0)
return;
for(var i = 0; i < n*n; i++) {
var dimension = width/n;
var cell = document.createElement('div');
cell.className = cell.className + ' gridCell';
cell.style.width = dimension + 'px';
cell.style.height = dimension + 'px';
container.appendChild(cell);
}
}
</script>
</body>
</html>
I am trying to generate a row of 16 boxes on load of webpage.
Here is my code:
var box = $("<div></div>").addClass("box");
$(document).ready(function(){
for(var i = 0; i < 16; i++) {
$("#container").append(box);
}
});
I also tried this within the for loop's code block:
if($("#container:contains(box)")) {
$(box).append(box);
}
I kind of understand why this does not work. That var box is only referencing an element and is not a copy of an element?
As you can likely tell, I'm new. I would really appreciate some pointers on how I can achieve this. Thanks.
Why not just use like this?
for(var i = 0; i < 16; i++) {
$("#container").append('<div class="box box-'+i+'" />');
}
You're appending the same div over and over. That will just move it (in this case, right back where it was). For a new div each time:
$(document).ready(function(){
var ctr = $('#container');
for(var i = 0; i < 16; i++) {
ctr.append("<div class='box'></div>");
}
});
$(document).ready(function() {
var ctr = $('#container');
for (var i = 0; i < 16; i++) {
ctr.append("<div class='box'></div>");
}
});
.box {
margin: 10px;
height: 25px;
width: 25px;
background-color: red;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container"></div>
I recommend against using append in a loop, bad performance. I suggest this:
var buffer = [];
for(var i = 0; i < 16; i++) {
buffer.push("<div class='box'></div>");
}
var html=buffer.join('');
$('#container').append(html);