Function not changing value of variable - javascript

I am working on an HTML page where I want function typewriter to be executed first and then for a loop to start that prints '.', to make it look like a loading screen.
This is the code I am using:
var y = 0
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
y = 1;
}
while (y == 1) {
var span = document.getElementById('myspan');
var int = setInterval(function() {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);
}
window.onload = typeWriter;
<div class="main d-none d-lg-block">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-1">Hi,<br>I'm Shalaj<span id="myspan"></span>
</h1>
<h1 id="typing" class="display-5" style="margin-top:30px;"></h1>
<h1 class="display-5" style="margin-top:100px;">
Prototyping = ["Arduino", "Raspberry Pi"]
<br> Languages = ["HTML", "CSS", "PYTHON", "C++"]
</h1>
</div>
</div>
</div>
The function typewriter() is getting executed but the code following it doesn't start, I assume this is because the value of y is not being set as 1. Could someone help me out here?
Thanks

Perhaps you could create another function that is called where y is being set:
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
} else {
typeEllipses();
}
}
function typeEllipses() {
var span = document.getElementById('myspan');
var int = setInterval(function() {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);
}
window.onload = typeWriter;
<div class="main d-none d-lg-block">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-1">Hi,<br>I'm Shalaj<span id="myspan"></span>
</h1>
<h1 id="typing" class="display-5" style="margin-top:30px;"></h1>
<h1 class="display-5" style="margin-top:100px;">
Prototyping = ["Arduino", "Raspberry Pi"]
<br> Languages = ["HTML", "CSS", "PYTHON", "C++"]
</h1>
</div>
</div>
</div>

You can see what is happening if you change
while(statement) {
//code
}
to
do{
//code
}while(statement)
The do...while loop only executes once. That's because it's being run one time on execution, at the time that y == 0. The while loop the way you have it never fires at all because the one time its statement is interpreted, y == 0.
If you want to call it every time typeWriter() is called, you already have a recursive loop for that function, so just put the while code in its own function and call it from inside there.
var y = 0
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
console.log(y)
y = 1;
}
do{
console.log("test")
/*var span = document.getElementById('myspan');
var int = setInterval(function() {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);*/
}while (y == 1)
window.onload = typeWriter;
<div id="typing"></div>

Hey try this No Need For Loop
If you use while loop of infinite it will crash.
so just use setInterval and clear the interval once theed for the loading is done clear the interval using clearInterval()
var y = 0
var i = 0;
var txt = '//Welcome To My Playground!';
var speed = 100;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
y = 1;
}
var span = document.getElementById('myspan');
var interval = setInterval(function () {
if ((span.innerHTML += '.').length == 11)
span.innerHTML = '';
}, 200);
window.onload = typeWriter;
<div class="main d-none d-lg-block">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-1">Hi,<br>I'm Shalaj<span id="myspan"></span>
</h1>
<h1 id="typing" class="display-5" style="margin-top:30px;"></h1>
<h1 class="display-5" style="margin-top:100px;">
Prototyping = ["Arduino", "Raspberry Pi"]
<br>
Languages = ["HTML", "CSS", "PYTHON", "C++"]
</h1>
</div>
</div>
</div>

Try this instead,
var i = 0;
var txt = "//Welcome To My Playground!";
var speed = 100;
var loading;
function typeWriter() {
if (i < txt.length) {
document.getElementById("typing").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
} else {
var span = document.getElementById("myspan");
var loading = setInterval(function () {
span.innerHTML = span.innerHTML.length == 11 ? "" : span.innerHTML;
span.innerHTML += ".";
}, speed);
// clearInterval(loading); // to stop loading dots
}
}

Related

Displaying hidden html buttons using JavaScript

Am trying to create a quiz but after the start page am un sure how to make the answer choices display. I have created the buttons for the choices in html and started them off as hidden, and have allocated for them in javascript. I have the questions and answers in an array but am stuck on displaying the choice buttons under the question. After the initial start page.
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.querySelector("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
var buttonEl = document.querySelector("start-game");
should be
var buttonEl = document.getElementById("start-game");
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
<div id="timer"></div>

How to decrement each click of the animation

I am trying to create animation game. Animation game must consits of One image alternating with another every half a second. I am intended to count++ on each click of the happy-face fish and count-- on each sad-face fish clicked. But, my code is only incrementing, whatever the image is clicked. Also,my code shows me two different images while It must have to be only one.
I have to count a click while my animation is running ( animation: images should be alternating every half a second. It will look like fish is smiling for half second and then crying for another half second then repeats). If i click on happy face, I will score 1 and if click on sad-face I will lose 1. In the end it must show you win if i achieve 10 and resets again on clicking Start Animation.
[Output should be like this:][1]
var image = "happy";
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
fish_img = document.getElementById("happy_fish");
f_img = document.getElementById("happy_fish");
fish_img.classList.add('on');
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
if (image == "happy") {
image = "sad";
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
} else {
image = "happy";
fish_img.src =
"https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
}
}
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="" id="sad_fish" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
I modified your StartAnimation and animationfunction methods to make the fish dissapear with a toggle instead of trying to modify the source of the image.
I made it with a css class off which will make a fish dissapear with display: none;
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
var initialWords = document.getElementById("d");
initialWords.innerHTML = "Your Score: <span id=\"score\">0</span>";
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
var fish_img = document.getElementById("happy_fish");
var f_img = document.getElementById("sad_fish");
fish_img.classList.toggle('off');
f_img.classList.toggle('off');
}
.off {
display: none;
}
<button onClick="StartAnimation()">Start Animation</button>
<br>
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="happy" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="sad" id="sad_fish" class="off" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
You can make things a lot simpler by having one img element and one click handler.
In the snippet I merged the two click handlers into one and added a check for the state of the fish (being represented now by the boolean isHappy).
I attached this handler to a single img element in your HTML and in the animation function I alternate its src attribute between the happy and sad fish according to the isHappy state.
Additionally, Since the counter and the total score are the same, I use only the total score variable.
var isHappy = true;
var totalscore;
var Schedule;
function clickFish() {
if (isHappy) {
totalscore++;
} else {
totalscore--;
}
var scoreSpan = document.getElementById("score");
scoreSpan.innerHTML = totalscore;
if (totalscore === 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + totalscore + " Game Over. You Win!";
}
}
function StartAnimation() {
isHappy = true
totalscore = 0;
clearInterval(Schedule);
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
fish_img = document.getElementById("fish");
isHappy = !isHappy;
if (isHappy) {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
} else {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
}
}
<button onclick="StartAnimation()">Start animation</button><br />
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="fish" onClick="clickFish()">
<br>
<h1 id="d">
Your Score:
<span id="score">0</span>
</h1>

JS onclick not executing for slideshow

I am trying to use W3.CSS Slideshow, the section "Slideshow Indicators".
However I need to create the previous and next buttons dynamically using JS.
But for some reason the prev and next buttons are not working..! (nothing happen onclick)
Here is my code:
HTML Code:
<title>Pre:D</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script src="script.js"></script>
</head>
<body>
<div class="w3-row-padding" style = "width: 800px" id="form">
<div class="mySlides">First Slide</div>
<div class="mySlides">Second Slide</div>
<div class="mySlides">Third Slide</div>
</div>
<div id="toggle" class="w3-center" style = "width: 800px">
</div>
</body>
Js Code:
var slideIndex = 1;
function plusDivs(n) {
showDivs(slideIndex += n);
}
function currentDiv(n) {
showDivs(slideIndex = n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
//var dots = document.getElementsByClassName("demo");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
window.onload=function(){
var dump = document.getElementById("toggle");
var sec = document.createElement("div");
sec.className = "w3-section";
var prev = document.createElement("button");
prev.className = "w3-btn";
prev.addEventListener("click", plusDivs(-1));
prev.innerHTML = "Previous";
var next = document.createElement("button");
next.className = "w3-btn";
next.addEventListener("click", plusDivs(1));
next.innerHTML = "Next";
sec.appendChild(prev);
sec.appendChild(next);
dump.appendChild(sec);
showDivs(slideIndex);
};
The buttons were working when created in the html file, but once I created them using js they got created but the onclick function doesn't work..
In case of passing parameters, bind it like prev.addEventListener("click", function() { plusDivs(-1) });
Here is an Example:
var slideIndex = 1;
function plusDivs(n) {
showDivs(slideIndex += n);
}
function currentDiv(n) {
showDivs(slideIndex = n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = x.length
}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex - 1].style.display = "block";
}
window.onload = function() {
var dump = document.getElementById("toggle");
var sec = document.createElement("div");
sec.className = "w3-section";
var prev = document.createElement("button");
prev.className = "w3-btn";
prev.addEventListener("click", function() {
plusDivs(-1)
});
prev.innerHTML = "Previous";
var next = document.createElement("button");
next.className = "w3-btn";
next.addEventListener("click", function() {
plusDivs(1)
});
next.innerHTML = "Next";
sec.appendChild(prev);
sec.appendChild(next);
dump.appendChild(sec);
showDivs(slideIndex);
};
<link href="http://www.w3schools.com/lib/w3.css" rel="stylesheet" />
<div class="w3-row-padding" style="width: 800px" id="form">
<div class="mySlides">First Slide</div>
<div class="mySlides">Second Slide</div>
<div class="mySlides">Third Slide</div>
</div>
<div id="toggle" class="w3-center" style="width: 800px">
</div>

Javascript: Namespace wrap up for normal function

I have created functions as normal way, am just trying this in namespace way. the below that i have now, for the same i just want to know how this would be in Namespace way. Any idea?
Aim: I want this piece of code in Namespace wrap up with optimization of this code.
<div class="Content" id="ThiPage">
<div class="something">
<p></p>
</div>
<div class="text">
<p></p>
<p></p>
</div>
</div>
<div class="Content" id="ThiPage1">
<div class="something">
<p></p>
</div>
<div class="text">
<p></p>
<p></p>
</div>
</div>
<div class="Content" id="ThiPage2">
<div class="something">
<p></p>
</div>
<div class="text">
<p></p>
<p></p>
</div>
</div>
My current JS code is
var sampPag = document.getElementById("ThiPage");
var sampPag1 = document.getElementById("ThiPage1");
var sampPag2 = document.getElementById("ThiPag2");
function samplefunct(thisArray){
sampPag.getElementsByTagName("div")[0].getElementsByTagName("p")[0].innerHTML = thisArray[1].heading;
sampPag1.getElementsByTagName("div")[0].getElementsByTagName("p")[0].innerHTML = thisArray[2].heading;
sampPag2.getElementsByTagName("div")[0].getElementsByTagName("p")[0].innerHTML = thisArray[0].heading;
//Body content
for(var i = 0; i < 20; i++){
sampPag.getElementsByTagName("div")[1].getElementsByTagName("p")[0].innerHTML += thisArray[1].text;
sampPag.getElementsByTagName("div")[1].getElementsByTagName("p")[1].innerHTML += thisArray[1].text;
if (i == 1) {sampPag.getElementsByTagName("div")[3].getElementsByTagName("img")[0].src += thisArray[1].image;}
sampPag1.getElementsByTagName("div")[1].getElementsByTagName("p")[0].innerHTML += thisArray[2].text;
sampPag1.getElementsByTagName("div")[1].getElementsByTagName("p")[1].innerHTML += thisArray[2].text;
if (i == 1) {sampPag1.getElementsByTagName("div")[2].getElementsByTagName("img")[0].src += thisArray[2].image;}
sampPag2.getElementsByTagName("div")[1].getElementsByTagName("p")[0].innerHTML += thisArray[0].text;
sampPag2.getElementsByTagName("div")[1].getElementsByTagName("p")[1].innerHTML += thisArray[0].text;
if (i == 1) {sampPag2.getElementsByTagName("div")[2].getElementsByTagName("img")[0].src += thisArray[0].image;}
}
}
You can easily move the fn into the new namespace. And add the js code in a separate external .js file.
var myns = {};
myns.globvar = {}; //global variables restricted to the namespace.
myns.funcs = {}; //Add your functions to the funcs.
myns.funcs.samplefunctest= function () {
/ * Code here */
}
Ref - http://addyosmani.com/resources/essentialjsdesignpatterns/book/#detailnamespacing
This could be as simple as an IIFE:
(function () {
var sampPag = document.getElementById('ThiPage');
var sampPag1 = document.getElementById('ThiPage1');
var sampPag2 = document.getElementById('ThiPag2');
function samplefunct(thisArray) {
sampPag.getElementsByTagName('div') [0].getElementsByTagName('p') [0].innerHTML = thisArray[1].heading;
sampPag1.getElementsByTagName('div') [0].getElementsByTagName('p') [0].innerHTML = thisArray[2].heading;
sampPag2.getElementsByTagName('div') [0].getElementsByTagName('p') [0].innerHTML = thisArray[0].heading;
//Body content
for (var i = 0; i < 20; i++) {
sampPag.getElementsByTagName('div') [1].getElementsByTagName('p') [0].innerHTML += thisArray[1].text;
sampPag.getElementsByTagName('div') [1].getElementsByTagName('p') [1].innerHTML += thisArray[1].text;
if (i == 1) {
sampPag.getElementsByTagName('div') [3].getElementsByTagName('img') [0].src += thisArray[1].image;
}
sampPag1.getElementsByTagName('div') [1].getElementsByTagName('p') [0].innerHTML += thisArray[2].text;
sampPag1.getElementsByTagName('div') [1].getElementsByTagName('p') [1].innerHTML += thisArray[2].text;
if (i == 1) {
sampPag1.getElementsByTagName('div') [2].getElementsByTagName('img') [0].src += thisArray[2].image;
}
sampPag2.getElementsByTagName('div') [1].getElementsByTagName('p') [0].innerHTML += thisArray[0].text;
sampPag2.getElementsByTagName('div') [1].getElementsByTagName('p') [1].innerHTML += thisArray[0].text;
if (i == 1) {
sampPag2.getElementsByTagName('div') [2].getElementsByTagName('img') [0].src += thisArray[0].image;
}
}
}
}());
This avoids creating any globals at all. One reference I use whenever considering module patterns is this page: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html. It has reasonable coverage of different JavaScript module patterns that exist.

code that displays words, JS Jquery

Code Link: http://jsbin.com/lozifokuzi/1/edit?html,js,output should display 16 words but it displays only 15 words (The words written in Hebrew).
The code is written in languages ​​JavaScript and jQuery.
$(document).ready(function () {
// creat array of objects, DetermineIDs
var words = new Array(16);
for (var i = 0; i < words.length; i++) {
words[i] = new Object();
words[i].id = i + 1;
}
//insert into objects words
words[0].word = "קוף";
words[1].word = "קוף";
words[2].word = "אריה";
words[3].word = "אריה";
words[4].word = "נמר";
words[5].word = "נמר";
words[6].word = "טלפון";
words[7].word = "טלפון";
words[8].word = "מחשב";
words[9].word = "מחשב";
words[10].word = "מקלדת";
words[11].word = "מקלדת";
words[12].word = "אוגר";
words[13].word = "אוגר";
words[14].word = "עכבר";
words[15].word = "עכבר";
//Determine locations
var ret=Random(loc);
var random = 0;
for (var i = 0; i < words.length; i++) {
words[i].loca=ret[0];
loc=ret[1];
ret = Random(loc);
}
//write the words
for (var i = 0; i < 16; i++) {
$("#c" + (words[i].loca)).html(words[i].word);
}
});
function RandomC(ezer, random) {
for (var i = 0; i <= 16; i++) {
if (ezer[i] == random) {
return true;
}
}
return false;
}
function Random(lq) {
var ezer = new Array(16);
for (var i = 0; i < 16; i++) {
ezer[i] = lq[i];
}
var random = 0;
while ((random < 1 || random > 17) || RandomC(ezer, random)) {
random = parseInt(Math.random() * 100);
}
for (var i = 0; i < lq.length; i++) {
if (lq[i] == null) {
ezer[i] = random;
break;
}
}
var arr = new Array(2);
arr[0] = random;
arr[1] = ezer;
return arr;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<article>
<div id="l1">
<p id="c1"></p>
<p id ="c2"></p>
<p id="c3"></p>
<p id="c4"></p>
</div>
<div id="l2">
<p id="c5"></p>
<p id="c6"></p>
<p id="c7"></p>
<p id="c8"></p>
</div>
<div id="l3">
<p id="c9"></p>
<p id="c10"></p>
<p id="c11"></p>
<p id="c12"></p>
</div>
<div id="l4">
<p id="c13"></p>
<p id="c14"></p>
<p id="c15"></p>
<p id="c16"></p>
</div>
</article>
</body>
</html>
Can anyone help?
You have 17 in funciton Random() while loop:
while ((random < 1 || random > 17) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
make it 16:
while ((random < 1 || random > 16) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
You problem is that you have 16 element from 1 to 16, and your random function gives 16 random numbers from 1 to 17, in case returned range has number 17 it lacks something from 1 to 16, which means your p element of that nubmer doesn't get filled with content.

Categories

Resources