Relative button - javascript

This quiz works on the computer, but when I try to use it on a Mobile phone the text is larger and condensed so the button stops working. I tried to change the .slide to relative and the .button top-margin to 30px, but the button stops working if the .slide is relative. So because that wasn't working I was trying to basically set the margin-top on the button large enough so it would always work.
Ideally the button is relative to the current question and appears about 30px below the answers. What am I doing wrong here? (Pertaining to the css, I know now my math was done very inefficiently.)
<style type="text/css">
body {
font-size: 20px;
font-family: 'Work Sans', sans-serif;
color: #333;
font-weight: 300;
text-align: center;
background-color: #f8f6f0;
}
h1 {
font-weight: 300;
margin: 0px;
padding: 10px;
font-size: 20px;
background-color: #444;
color: #fff;
}
.section-description {
margin-bottom: 20px;
}
.question {
position: relative;
font-size: 30px;
margin-bottom: 10px;
}
.answers {
position: relative;
margin-bottom: 20px;
text-align: left;
display: inline-block;
}
.answers label {
display: block;
margin-bottom: 10px;
}
button {
position: relative;
font-family: 'Work Sans', sans-serif;
font-size: 22px;
background-color: #279;
color: #fff;
border: 0px;
border-radius: 3px;
padding: 20px;
cursor: pointer;
margin-top: 350px;
margin-bottom: 0px;
}
button:hover {
background-color: #38a;
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
z-index: 1;
opacity: 0;
transition: opacity 0.5s;
}
.active-slide {
opacity: 1;
z-index: 2;
}
.quiz-container {
position: relative;
height: 200px;
margin-top: 60px;
}
</style>
<h1>ASVAB PRETEST</h1>
<meta name="viewport" content="width=device-width, initial-scale=1">
<div class="quiz-container">
<div id="quiz"> </div>
</div>
<p><button id="previous" type="button">Previous Question</button><button id="next" type="button">Next Question</button><button id="submit" type="button">Submit Quiz</button></p>
<div id="results"> </div>
<div id="results"> </div>
<div id="category-scores"> </div>
<div id="raw-scores"> </div>
<script>
// variable for categories
const resultsContainer = document.getElementById('results');
const categoryScoresContainer = document.getElementById('category-scores');
const rawScoresContainer = document.getElementById('raw-scores');
const quizContainer = document.getElementById("quiz");
const submitButton = document.getElementById("submit");
(function() {
// Functions
function buildQuiz() {
// variable to store the HTML output
const output = [];
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
// variable to store the list of possible answers
const answers = [];
// and for each available answer...
for (letter in currentQuestion.answers) {
// ...add an HTML radio button
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`
);
}
// add this question and its answers to the output
output.push(
`<div class="slide">
${currentQuestion.description ? `<div class="section-description">${currentQuestion.description}</div>` : ''}
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>
</div>`
);
});
// combine output list into one string of HTML and put it on the page
quizContainer.innerHTML = output.join("");
const nextButton = document.getElementById("next");
nextButton.addEventListener("click", function() {
const description = document.getElementById("description");
if (description) quizContainer.removeChild(description);
});
}
function showResults() {
// gather answer containers from our quiz
const answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
let numCorrect = 0;
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
// if answer is correct
if (userAnswer === currentQuestion.correctAnswer) {
// add to the number of correct answers
numCorrect++;
scores[currentQuestion.category]++;
//multiplies by 2 for final result
scores[currentQuestion.category]++;
}
});
//hide myQuestions
quizContainer.innerHTML = "";
//calculate VE
let ve = scores.wk + scores.pc;
let finalve;
if (ve === 0) {
finalve = 20;
} else if (ve === 2) {
finalve = 40;
} else if (ve === 4) {
finalve = 42;
} else if (ve === 6) {
finalve = 46;
} else if (ve === 8) {
finalve = 50;
} else if (ve === 10) {
finalve = 54;
} else if (ve === 12) {
finalve = 56;
} else if (ve === 14) {
finalve = 60;
} else if (ve === 16) {
finalve = 64;
} else if (ve === 18) {
finalve = 66;
} else if (ve === 20) {
finalve = 70;
} else if (ve === 22) {
finalve = 74;
} else if (ve === 24) {
finalve = 78;
} else if (ve === 26) {
finalve = 80;
} else if (ve === 28) {
finalve = 84;
} else if (ve === 30) {
finalve = 88;
} else if (ve === 32) {
finalve = 90;
} else if (ve === 34) {
finalve = 94;
} else if (ve === 36) {
finalve = 98;
} else if (ve === 38) {
finalve = 100;
} else if (ve === 40) {
finalve = 104;
} else if (ve === 42) {
finalve = 108;
} else if (ve === 44) {
finalve = 112;
} else if (ve === 46) {
finalve = 114;
} else if (ve === 48) {
finalve = 118;
} else if (ve === 50) {
finalve = 122;
} else if (ve === 52) {
finalve = 122;
} else {
// Handle any other cases
}
//calculate ar
let ar = scores.ar;
let finalar;
if (ar === 0) {
finalar = 26;
} else if (ar === 2) {
finalar = 27;
} else if (ar === 4) {
finalar = 30;
} else if (ar === 6) {
finalar = 32;
} else if (ar === 8) {
finalar = 35;
} else if (ar === 10) {
finalar = 38;
} else if (ar === 12) {
finalar = 41;
} else if (ar === 14) {
finalar = 44;
} else if (ar === 16) {
finalar = 47;
} else if (ar === 18) {
finalar = 49;
} else if (ar === 20) {
finalar = 52;
} else if (ar === 22) {
finalar = 55;
} else if (ar === 24) {
finalar = 58;
} else if (ar === 26) {
finalar = 61;
} else if (ar === 28) {
finalar = 63;
} else if (ar === 30) {
finalar = 66;
} else {
// Handle any other cases
}
let mk = scores.mk;
let finalmk;
if (mk === 0) {
finalmk = 29;
} else if (mk === 2) {
finalmk = 31;
} else if (mk === 4) {
finalmk = 34;
} else if (mk === 6) {
finalmk = 37;
} else if (mk === 8) {
finalmk = 41;
} else if (mk === 10) {
finalmk = 44;
} else if (mk === 12) {
finalmk = 47;
} else if (mk === 14) {
finalmk = 50;
} else if (mk === 16) {
finalmk = 53;
} else if (mk === 18) {
finalmk = 57;
} else if (mk === 20) {
finalmk = 60;
} else if (mk === 22) {
finalmk = 63;
} else if (mk === 24) {
finalmk = 66;
} else if (mk === 26) {
finalmk = 88;
} else {
// Handle any other cases
}
//calculates std
let std = finalve + finalar + finalmk;
//converts std to pct
let pct;
if (std >= 80 && std <= 120) {
pct = 1;
} else if (std >= 121 && std <= 124) {
pct = 2;
} else if (std >= 125 && std <= 127) {
pct = 3;
} else if (std >= 128 && std <= 131) {
pct = 4;
} else if (std >= 132 && std <= 134) {
pct = 5;
} else if (std >= 135 && std <= 137) {
pct = 6;
} else if (std >= 138 && std <= 139) {
pct = 7;
} else if (std >= 140 && std <= 142) {
pct = 8;
} else if (std >= 143 && std <= 144) {
pct = 9;
} else if (std >= 145 && std <= 146) {
pct = 10;
} else if (std >= 147 && std <= 148) {
pct = 11;
} else if (std >= 149 && std <= 150) {
pct = 12;
} else if (std >= 151 && std <= 153) {
pct = 13;
} else if (std === 154) {
pct = 14;
} else if (std >= 155 && std <= 156) {
pct = 15;
} else if (std >= 157 && std <= 158) {
pct = 16;
} else if (std >= 159 && std <= 160) {
pct = 17;
} else if (std >= 161 && std <= 162) {
pct = 18;
} else if (std >= 163 && std <= 164) {
pct = 19;
} else if (std === 165) {
pct = 20;
} else if (std >= 166 && std <= 167) {
pct = 21;
} else if (std >= 168 && std <= 169) {
pct = 22;
} else if (std >= 170 && std <= 171) {
pct = 23;
} else if (std === 172) {
pct = 24;
} else if (std === 173) {
pct = 25;
} else if (std >= 174 && std <= 175) {
pct = 26;
} else if (std >= 176 && std <= 177) {
pct = 27;
} else if (std === 178) {
pct = 28;
} else if (std === 179) {
pct = 29;
} else if (std === 181) {
pct = 30;
} else if (std === 182) {
pct = 31;
} else if (std >= 183 && std <= 184) {
pct = 32;
} else if (std === 185) {
pct = 33;
} else if (std === 186) {
pct = 34;
} else if (std >= 187 && std <= 188) {
pct = 35;
} else if (std === 189) {
pct = 36;
} else if (std === 190) {
pct = 37;
} else if (std === 191) {
pct = 38;
} else if (std === 192) {
pct = 39;
} else if (std === 193) {
pct = 40;
} else if (std === 194) {
pct = 41;
} else if (std >= 195 && std <= 196) {
pct = 42;
} else if (std === 197) {
pct = 43;
} else if (std === 198) {
pct = 44;
} else if (std === 199) {
pct = 45;
} else if (std === 200) {
pct = 46;
} else if (std === 201) {
pct = 47;
} else if (std === 202) {
pct = 48;
} else if (std === 203) {
pct = 49;
} else if (std === 204) {
pct = 50;
} else if (std === 205) {
pct = 51;
} else if (std === 206) {
pct = 52;
} else if (std >= 207 && std <= 208) {
pct = 53;
} else if (std === 209) {
pct = 54;
} else if (std === 210) {
pct = 55;
} else if (std === 211) {
pct = 56;
} else if (std === 212) {
pct = 57;
} else if (std === 213) {
pct = 58;
} else if (std === 214) {
pct = 60;
} else if (std === 215) {
pct = 61;
} else if (std === 216) {
pct = 62;
} else if (std === 217) {
pct = 63;
} else if (std === 218) {
pct = 64;
} else if (std === 219) {
pct = 65;
} else if (std === 220) {
pct = 66;
} else if (std === 221) {
pct = 67;
} else if (std === 222) {
pct = 68;
} else if (std === 223) {
pct = 69;
} else if (std === 224) {
pct = 70;
} else if (std === 225) {
pct = 71;
} else if (std === 226) {
pct = 72;
} else if (std === 227) {
pct = 73;
} else if (std === 228) {
pct = 74;
} else if (std === 229) {
pct = 75;
} else if (std === 230) {
pct = 76;
} else if (std === 231) {
pct = 77;
} else if (std === 232) {
pct = 78;
} else if (std === 233) {
pct = 79;
} else if (std >= 234 && std <= 235) {
pct = 80;
} else if (std === 236) {
pct = 81;
} else if (std === 237) {
pct = 82;
} else if (std === 238) {
pct = 83;
} else if (std === 239) {
pct = 84;
} else if (std === 240) {
pct = 85;
} else if (std === 241) {
pct = 86;
} else if (std === 242) {
pct = 87;
} else if (std === 243) {
pct = 88;
} else if (std === 244) {
pct = 89;
} else if (std === 245) {
pct = 90;
} else if (std === 246) {
pct = 91;
} else if (std === 247) {
pct = 92;
} else if (std === 248) {
pct = 93;
} else if (std === 249) {
pct = 94;
} else if (std === 250) {
pct = 95;
} else if (std === 251) {
pct = 96;
} else if (std === 252) {
pct = 97;
} else if (std === 253) {
pct = 98;
} else if (std >= 254 && std <= 320) {
pct = 99;
} else {
// Handle any other cases
}
// show number of correct answers out of total
resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
categoryScoresContainer.innerHTML = `
<p>
<b>Screenshot this page and send it to your recruiter.</b>
</p>
<p>Your estimated AFQT score is ${pct}</p><br /><br />
<p>Word Knowledge = ${scores.wk/2} out of 18</p>
<p>Arithmetic Reasoning = ${scores.ar/2} out of 15</p>
<p>Paragraph Comprehension = ${scores.pc/2} out of 8</p>
<p>Mathmematics Knowledge = ${scores.mk/2} out of 13</p>`;
// hide previous, next and submit button, and make quiz read-only
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const submitButton = document.getElementById("submit");
previousButton.style.display = "none";
nextButton.style.display = "none";
submitButton.style.display = "none";
const inputElements = quizContainer.querySelectorAll("input");
inputElements.forEach(input => {
input.setAttribute("disabled", true);
});
//add restart button
const restartButton = document.getElementById("restart");
restartButton.style.display = "block";
restartButton.addEventListener("click", function() {
location.reload();
});
}
function showSlide(n) {
slides[currentSlide].classList.remove('active-slide');
slides[n].classList.add('active-slide');
currentSlide = n;
if (currentSlide === 0) {
previousButton.style.display = 'none';
} else {
previousButton.style.display = 'inline-block';
}
if (currentSlide === slides.length - 1) {
nextButton.style.display = 'none';
submitButton.style.display = 'inline-block';
} else {
nextButton.style.display = 'inline-block';
submitButton.style.display = 'none';
}
}
function showNextSlide() {
showSlide(currentSlide + 1);
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
// Variables
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');
const myQuestions = [{
category: "wk",
description: "<h2>PART I - WORD KNOWLEDGE. YOU WILL HAVE 7 MINUTES TO COMPLETE.</h2>",
question: "1. <b><u>SMALL</u></b> MOST NEARLY MEANS?",
answers: {
a: "STURDY",
b: "ROUND",
c: "CHEAP",
d: "LITTLE"
},
correctAnswer: "d"
},
{
category: "ar",
description: "<h2>PART II - ARITHMETIC REASONING - YOU WILL HAVE FOURTEEN (14) MINUTES:</h2>",
question: "1. TWO AUTOMOBILES START TOGETHER FROM THE SAME PLACE AND TRAVEL ALONG THE SAME ROUTE. THE FIRST AVERAGES 40 MPH. THE SECOND 55 MPH. HOW MANY MILES FURTHER ALONG THE ROUTE IS THE SECOND AUTO AT THE END OF THE 5TH HOUR?",
answers: {
a: "55 x 5",
b: "55 - 40",
c: "(55x5) - (40x5)",
d: "55/5 - 40/5"
},
correctAnswer: "c"
},
{
category: "pc",
description: "<h2>PART III - PARAGRAPH COMPREHENSION - YOU WILL HAVE SEVEN (7) MINUTES:</h2>",
question: "1. THE DUTY OF THE LIGHTHOUSE KEEPER IS TO KEEP THE LIGHT BURNING NO MATTER WHAT HAPPENS, SO THAT SHIPS WILL BE WARNED OF THE PRESENCE OF DANGEROUS ROCKS. IF A SHIPWRECK SHOULD OCCUR NEAR THE LIGHTHOUSE, EVEN THOUGH HE WOULD LIKE TO AID IN THE RESCUE OF IT'S CREW AND PASSENGERS, THE LIGHTHOUSE KEEPER MUST......",
answers: {
a: "STAY AT HIS LIGHT",
b: "RUSH TO THEIR AID",
c: "TURN OUT THE LIGHT",
d: "QUICKLY SOUND THE SIREN"
},
correctAnswer: "a"
},
{
category: "mk",
description: "<h2>PART IV - MATHEMATICS KNOWLEDGE - YOU WILL HAVE TWELVE (12) MINUTES:</h2>",
question: "1. WHICH OF THE FOLLOWING IS THE SMALLEST PRIME NUMBER GREATER THAN 200?",
answers: {
a: "201",
b: "205",
c: "211",
d: "214"
},
correctAnswer: "c"
},
];
// Kick things off
buildQuiz();
// Pagination
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
let scores = {
wk: 0,
ar: 0,
pc: 0,
mk: 0,
};
// Show the first slide
showSlide(currentSlide);
// Event listeners
submitButton.addEventListener('click', showResults);
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
})();
</script>

I changed three things about your code:
The first thing is I enabled the button to click, the solution is to add z-index into the CSS. Please notice that do not set the value as 99999 because it will be hard for you to maintain the website. For example, if you want to add something else that is above the button(such as login to take next question or something like that), you have to set new elements' z-index as 99999999
The second thing I changed is changing p into div because you use buttons in p and that will not work in some cases.
The last thing is to let the ButtonDIV at the bottom by using top:calc(100vh - 10px); (Your requirement), and now it is at the bottom.
Here is the code:
<style type="text/css">
body {
font-size: 20px;
font-family: 'Work Sans', sans-serif;
color: #333;
font-weight: 300;
text-align: center;
background-color: #f8f6f0;
}
h1 {
font-weight: 300;
margin: 0px;
padding: 10px;
font-size: 20px;
background-color: #444;
color: #fff;
}
.section-description {
margin-bottom: 20px;
}
.question {
position: relative;
font-size: 30px;
margin-bottom: 10px;
}
.answers {
position: relative;
margin-bottom: 20px;
text-align: left;
display: inline-block;
}
.answers label {
display: block;
margin-bottom: 10px;
}
button {
position: relative;
font-family: 'Work Sans', sans-serif;
font-size: 22px;
background-color: #279;
color: #fff;
border: 0px;
border-radius: 3px;
padding: 20px;
cursor: pointer;
margin-top: 350px;
margin-bottom: 0px;
z-index:100;
}
button:hover {
background-color: #38a;
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
z-index: 1;
opacity: 0;
transition: opacity 0.5s;
}
.active-slide {
opacity: 1;
z-index: 2;
}
.quiz-container {
position: relative;
height: 200px;
margin-top: 60px;
}
#BUTTONDIV{
margin-bottom: 0;
top:calc(100vh - 10px);
height:300px;
position:relative;
}
</style>
<h1>ASVAB PRETEST</h1>
<meta name="viewport" content="width=device-width, initial-scale=1">
<div class="quiz-container">
<div id="quiz"> </div>
</div>
<div id="BUTTONDIV"><button id="previous" type="button">Previous Question</button><button id="next" type="button">Next Question</button><button id="submit" type="button">Submit Quiz</button></div>
<!--Do not use p here, instead, you are suppoesed to use div-->
<div id="results"> </div>
<div id="results"> </div>
<div id="category-scores"> </div>
<div id="raw-scores"> </div>
<script>
// variable for categories
const resultsContainer = document.getElementById('results');
const categoryScoresContainer = document.getElementById('category-scores');
const rawScoresContainer = document.getElementById('raw-scores');
const quizContainer = document.getElementById("quiz");
const submitButton = document.getElementById("submit");
(function() {
// Functions
function buildQuiz() {
// variable to store the HTML output
const output = [];
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
// variable to store the list of possible answers
const answers = [];
// and for each available answer...
for (letter in currentQuestion.answers) {
// ...add an HTML radio button
answers.push(
`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`
);
}
// add this question and its answers to the output
output.push(
`<div class="slide">
${currentQuestion.description ? `<div class="section-description">${currentQuestion.description}</div>` : ''}
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>
</div>`
);
});
// combine output list into one string of HTML and put it on the page
quizContainer.innerHTML = output.join("");
const nextButton = document.getElementById("next");
nextButton.addEventListener("click", function() {
const description = document.getElementById("description");
if (description) quizContainer.removeChild(description);
});
}
function showResults() {
// gather answer containers from our quiz
const answerContainers = quizContainer.querySelectorAll('.answers');
// keep track of user's answers
let numCorrect = 0;
// for each question...
myQuestions.forEach((currentQuestion, questionNumber) => {
// find selected answer
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).value;
// if answer is correct
if (userAnswer === currentQuestion.correctAnswer) {
// add to the number of correct answers
numCorrect++;
scores[currentQuestion.category]++;
//multiplies by 2 for final result
scores[currentQuestion.category]++;
}
});
//hide myQuestions
quizContainer.innerHTML = "";
//calculate VE
let ve = scores.wk + scores.pc;
let finalve;
if (ve === 0) {
finalve = 20;
} else if (ve === 2) {
finalve = 40;
} else if (ve === 4) {
finalve = 42;
} else if (ve === 6) {
finalve = 46;
} else if (ve === 8) {
finalve = 50;
} else if (ve === 10) {
finalve = 54;
} else if (ve === 12) {
finalve = 56;
} else if (ve === 14) {
finalve = 60;
} else if (ve === 16) {
finalve = 64;
} else if (ve === 18) {
finalve = 66;
} else if (ve === 20) {
finalve = 70;
} else if (ve === 22) {
finalve = 74;
} else if (ve === 24) {
finalve = 78;
} else if (ve === 26) {
finalve = 80;
} else if (ve === 28) {
finalve = 84;
} else if (ve === 30) {
finalve = 88;
} else if (ve === 32) {
finalve = 90;
} else if (ve === 34) {
finalve = 94;
} else if (ve === 36) {
finalve = 98;
} else if (ve === 38) {
finalve = 100;
} else if (ve === 40) {
finalve = 104;
} else if (ve === 42) {
finalve = 108;
} else if (ve === 44) {
finalve = 112;
} else if (ve === 46) {
finalve = 114;
} else if (ve === 48) {
finalve = 118;
} else if (ve === 50) {
finalve = 122;
} else if (ve === 52) {
finalve = 122;
} else {
// Handle any other cases
}
//calculate ar
let ar = scores.ar;
let finalar;
if (ar === 0) {
finalar = 26;
} else if (ar === 2) {
finalar = 27;
} else if (ar === 4) {
finalar = 30;
} else if (ar === 6) {
finalar = 32;
} else if (ar === 8) {
finalar = 35;
} else if (ar === 10) {
finalar = 38;
} else if (ar === 12) {
finalar = 41;
} else if (ar === 14) {
finalar = 44;
} else if (ar === 16) {
finalar = 47;
} else if (ar === 18) {
finalar = 49;
} else if (ar === 20) {
finalar = 52;
} else if (ar === 22) {
finalar = 55;
} else if (ar === 24) {
finalar = 58;
} else if (ar === 26) {
finalar = 61;
} else if (ar === 28) {
finalar = 63;
} else if (ar === 30) {
finalar = 66;
} else {
// Handle any other cases
}
let mk = scores.mk;
let finalmk;
if (mk === 0) {
finalmk = 29;
} else if (mk === 2) {
finalmk = 31;
} else if (mk === 4) {
finalmk = 34;
} else if (mk === 6) {
finalmk = 37;
} else if (mk === 8) {
finalmk = 41;
} else if (mk === 10) {
finalmk = 44;
} else if (mk === 12) {
finalmk = 47;
} else if (mk === 14) {
finalmk = 50;
} else if (mk === 16) {
finalmk = 53;
} else if (mk === 18) {
finalmk = 57;
} else if (mk === 20) {
finalmk = 60;
} else if (mk === 22) {
finalmk = 63;
} else if (mk === 24) {
finalmk = 66;
} else if (mk === 26) {
finalmk = 88;
} else {
// Handle any other cases
}
//calculates std
let std = finalve + finalar + finalmk;
//converts std to pct
let pct;
if (std >= 80 && std <= 120) {
pct = 1;
} else if (std >= 121 && std <= 124) {
pct = 2;
} else if (std >= 125 && std <= 127) {
pct = 3;
} else if (std >= 128 && std <= 131) {
pct = 4;
} else if (std >= 132 && std <= 134) {
pct = 5;
} else if (std >= 135 && std <= 137) {
pct = 6;
} else if (std >= 138 && std <= 139) {
pct = 7;
} else if (std >= 140 && std <= 142) {
pct = 8;
} else if (std >= 143 && std <= 144) {
pct = 9;
} else if (std >= 145 && std <= 146) {
pct = 10;
} else if (std >= 147 && std <= 148) {
pct = 11;
} else if (std >= 149 && std <= 150) {
pct = 12;
} else if (std >= 151 && std <= 153) {
pct = 13;
} else if (std === 154) {
pct = 14;
} else if (std >= 155 && std <= 156) {
pct = 15;
} else if (std >= 157 && std <= 158) {
pct = 16;
} else if (std >= 159 && std <= 160) {
pct = 17;
} else if (std >= 161 && std <= 162) {
pct = 18;
} else if (std >= 163 && std <= 164) {
pct = 19;
} else if (std === 165) {
pct = 20;
} else if (std >= 166 && std <= 167) {
pct = 21;
} else if (std >= 168 && std <= 169) {
pct = 22;
} else if (std >= 170 && std <= 171) {
pct = 23;
} else if (std === 172) {
pct = 24;
} else if (std === 173) {
pct = 25;
} else if (std >= 174 && std <= 175) {
pct = 26;
} else if (std >= 176 && std <= 177) {
pct = 27;
} else if (std === 178) {
pct = 28;
} else if (std === 179) {
pct = 29;
} else if (std === 181) {
pct = 30;
} else if (std === 182) {
pct = 31;
} else if (std >= 183 && std <= 184) {
pct = 32;
} else if (std === 185) {
pct = 33;
} else if (std === 186) {
pct = 34;
} else if (std >= 187 && std <= 188) {
pct = 35;
} else if (std === 189) {
pct = 36;
} else if (std === 190) {
pct = 37;
} else if (std === 191) {
pct = 38;
} else if (std === 192) {
pct = 39;
} else if (std === 193) {
pct = 40;
} else if (std === 194) {
pct = 41;
} else if (std >= 195 && std <= 196) {
pct = 42;
} else if (std === 197) {
pct = 43;
} else if (std === 198) {
pct = 44;
} else if (std === 199) {
pct = 45;
} else if (std === 200) {
pct = 46;
} else if (std === 201) {
pct = 47;
} else if (std === 202) {
pct = 48;
} else if (std === 203) {
pct = 49;
} else if (std === 204) {
pct = 50;
} else if (std === 205) {
pct = 51;
} else if (std === 206) {
pct = 52;
} else if (std >= 207 && std <= 208) {
pct = 53;
} else if (std === 209) {
pct = 54;
} else if (std === 210) {
pct = 55;
} else if (std === 211) {
pct = 56;
} else if (std === 212) {
pct = 57;
} else if (std === 213) {
pct = 58;
} else if (std === 214) {
pct = 60;
} else if (std === 215) {
pct = 61;
} else if (std === 216) {
pct = 62;
} else if (std === 217) {
pct = 63;
} else if (std === 218) {
pct = 64;
} else if (std === 219) {
pct = 65;
} else if (std === 220) {
pct = 66;
} else if (std === 221) {
pct = 67;
} else if (std === 222) {
pct = 68;
} else if (std === 223) {
pct = 69;
} else if (std === 224) {
pct = 70;
} else if (std === 225) {
pct = 71;
} else if (std === 226) {
pct = 72;
} else if (std === 227) {
pct = 73;
} else if (std === 228) {
pct = 74;
} else if (std === 229) {
pct = 75;
} else if (std === 230) {
pct = 76;
} else if (std === 231) {
pct = 77;
} else if (std === 232) {
pct = 78;
} else if (std === 233) {
pct = 79;
} else if (std >= 234 && std <= 235) {
pct = 80;
} else if (std === 236) {
pct = 81;
} else if (std === 237) {
pct = 82;
} else if (std === 238) {
pct = 83;
} else if (std === 239) {
pct = 84;
} else if (std === 240) {
pct = 85;
} else if (std === 241) {
pct = 86;
} else if (std === 242) {
pct = 87;
} else if (std === 243) {
pct = 88;
} else if (std === 244) {
pct = 89;
} else if (std === 245) {
pct = 90;
} else if (std === 246) {
pct = 91;
} else if (std === 247) {
pct = 92;
} else if (std === 248) {
pct = 93;
} else if (std === 249) {
pct = 94;
} else if (std === 250) {
pct = 95;
} else if (std === 251) {
pct = 96;
} else if (std === 252) {
pct = 97;
} else if (std === 253) {
pct = 98;
} else if (std >= 254 && std <= 320) {
pct = 99;
} else {
// Handle any other cases
}
// show number of correct answers out of total
resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
categoryScoresContainer.innerHTML = `
<p>
<b>Screenshot this page and send it to your recruiter.</b>
</p>
<p>Your estimated AFQT score is ${pct}</p><br /><br />
<p>Word Knowledge = ${scores.wk/2} out of 18</p>
<p>Arithmetic Reasoning = ${scores.ar/2} out of 15</p>
<p>Paragraph Comprehension = ${scores.pc/2} out of 8</p>
<p>Mathmematics Knowledge = ${scores.mk/2} out of 13</p>`;
// hide previous, next and submit button, and make quiz read-only
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const submitButton = document.getElementById("submit");
previousButton.style.display = "none";
nextButton.style.display = "none";
submitButton.style.display = "none";
const inputElements = quizContainer.querySelectorAll("input");
inputElements.forEach(input => {
input.setAttribute("disabled", true);
});
//add restart button
const restartButton = document.getElementById("restart");
restartButton.style.display = "block";
restartButton.addEventListener("click", function() {
location.reload();
});
}
function showSlide(n) {
slides[currentSlide].classList.remove('active-slide');
slides[n].classList.add('active-slide');
currentSlide = n;
if (currentSlide === 0) {
previousButton.style.display = 'none';
} else {
previousButton.style.display = 'inline-block';
}
if (currentSlide === slides.length - 1) {
nextButton.style.display = 'none';
submitButton.style.display = 'inline-block';
} else {
nextButton.style.display = 'inline-block';
submitButton.style.display = 'none';
}
}
function showNextSlide() {
showSlide(currentSlide + 1);
}
function showPreviousSlide() {
showSlide(currentSlide - 1);
}
// Variables
const quizContainer = document.getElementById('quiz');
const resultsContainer = document.getElementById('results');
const submitButton = document.getElementById('submit');
const myQuestions = [{
category: "wk",
description: "<h2>PART I - WORD KNOWLEDGE. YOU WILL HAVE 7 MINUTES TO COMPLETE.</h2>",
question: "1. <b><u>SMALL</u></b> MOST NEARLY MEANS?",
answers: {
a: "STURDY",
b: "ROUND",
c: "CHEAP",
d: "LITTLE"
},
correctAnswer: "d"
},
{
category: "ar",
description: "<h2>PART II - ARITHMETIC REASONING - YOU WILL HAVE FOURTEEN (14) MINUTES:</h2>",
question: "1. TWO AUTOMOBILES START TOGETHER FROM THE SAME PLACE AND TRAVEL ALONG THE SAME ROUTE. THE FIRST AVERAGES 40 MPH. THE SECOND 55 MPH. HOW MANY MILES FURTHER ALONG THE ROUTE IS THE SECOND AUTO AT THE END OF THE 5TH HOUR?",
answers: {
a: "55 x 5",
b: "55 - 40",
c: "(55x5) - (40x5)",
d: "55/5 - 40/5"
},
correctAnswer: "c"
},
{
category: "pc",
description: "<h2>PART III - PARAGRAPH COMPREHENSION - YOU WILL HAVE SEVEN (7) MINUTES:</h2>",
question: "1. THE DUTY OF THE LIGHTHOUSE KEEPER IS TO KEEP THE LIGHT BURNING NO MATTER WHAT HAPPENS, SO THAT SHIPS WILL BE WARNED OF THE PRESENCE OF DANGEROUS ROCKS. IF A SHIPWRECK SHOULD OCCUR NEAR THE LIGHTHOUSE, EVEN THOUGH HE WOULD LIKE TO AID IN THE RESCUE OF IT'S CREW AND PASSENGERS, THE LIGHTHOUSE KEEPER MUST......",
answers: {
a: "STAY AT HIS LIGHT",
b: "RUSH TO THEIR AID",
c: "TURN OUT THE LIGHT",
d: "QUICKLY SOUND THE SIREN"
},
correctAnswer: "a"
},
{
category: "mk",
description: "<h2>PART IV - MATHEMATICS KNOWLEDGE - YOU WILL HAVE TWELVE (12) MINUTES:</h2>",
question: "1. WHICH OF THE FOLLOWING IS THE SMALLEST PRIME NUMBER GREATER THAN 200?",
answers: {
a: "201",
b: "205",
c: "211",
d: "214"
},
correctAnswer: "c"
},
];
// Kick things off
buildQuiz();
// Pagination
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
let scores = {
wk: 0,
ar: 0,
pc: 0,
mk: 0,
};
// Show the first slide
showSlide(currentSlide);
// Event listeners
submitButton.addEventListener('click', showResults);
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
})();
</script>

Related

Background Error fault when applying condition

So if x = Number value background changes fine, my question is when x has no value. How can I have a background-color of #ffffff. Currently, code is defaulting to #db0000.
JS:
var grid_value = document.getElementById("Vone").innerHTML;
var x = grid_value;
if (x >= 0 && x < 15) {
document.getElementById("GridA").style.backgroundColor = "#db0000";
} else if (x >= 15 && x < 25) {
document.getElementById("GridA").style.backgroundColor = "#f0ad4e";
} else if (x >= 25) {
document.getElementById("GridA").style.backgroundColor = "#5cb85c";
} else if (x = "Pick" ) {
document.getElementById("GridA").style.backgroundColor = "#0085eb";
} else if (x = "" ) {
document.getElementById("GridA").style.backgroundColor = "#ffffff";
}
Here you haven't given any conditions if x doesn't have a value, so the default condition is x=0.
You should try else if (!x).
else if (!x) {
document.getElementById("GridA").style.backgroundColor = "#ffffff";
}
Hope this helps you out.
const gA = document.getElementById("GridA");
document.getElementById("Vone").addEventListener("blur", function(event){
gA.classList = "";
var x = this.value;
if (x === "") {
gA.classList.add("white");
} else if (x === "Pick") {
gA.classList.add("color1");
} else if (x >= 0 && x < 15) {
gA.classList.add("color2");
} else if (x >= 15 && x < 25) {
gA.classList.add("color3");
} else if (x >= 25) {
gA.classList.add("color4");
}
});
#GridA { height:100px; border:1px solid grey; margin-top:5px; }
.color1 { background-color:#dbf000; }
.color2 { background-color:#f0ad4e; }
.color3 { background-color:#5cb85c; }
.color4 { background-color:#0085eb; }
.white { background-color:#ffffff; }
<input id="Vone">
<div id="GridA"></div>

I am sticking to the walls but only on the right

I am currently debugging a game im making in p5.js and have found that i stick to walls that are on the right of my player but not on my left. i have tried turning up the number of pixels away it checks but it doesn't look good and only will work with 5. here is the code:
move(){
let wallcheckL = get(this.x - 1, this.y);
let wallcheckR = get(this.x + (this.scale + 1), this.y);
let wallcheckLB = get(this.x - 1, this.y + this.scale - 5);
let wallcheckRB = get(this.x + (this.scale + 1), this.y + this.scale - 5);
if(wallcheckL[0] == 0 && wallcheckL[1] == 0 && wallcheckL[2] == 255 ||
this.x == 0 ||
wallcheckLB[0] == 0 && wallcheckLB[1] == 0 && wallcheckLB[2] == 255 ||
wallcheckL[0] == 0 && wallcheckL[1] == 128 && wallcheckL[2] == 0) {
this.wallL = true;
}
else{
this.wallL = false;
}
if(wallcheckR[0] == 0 && wallcheckR[1] == 0 && wallcheckR[2] == 255 ||
this.x == 400 - this.scale ||
wallcheckRB[0] == 0 && wallcheckRB[1] == 0 && wallcheckRB[2] == 255 ||
wallcheckR[0] == 0 && wallcheckR[1] == 128 && wallcheckR[2] == 0) {
this.wallR = true;
}
else{
this.wallR = false;
}
if(this.moveR == true && this.wallR == false){
this.x += this.speed;
}
else if(this.moveL == true && this.wallL == false){
this.x -= this.speed;
}
}
also here is the gravity:
gravity(){
let gc = get(this.x, this.y + 21);
let gc2 = get(this.x + this.scale, this.y + 21);
if(gc[0] == 0 && gc[1] == 0 && gc[2] == 255 && gc[3] == 255 ||
this.y >= 400 - this.scale ||
gc2[0] == 0 && gc2[1] == 0 && gc2[2] == 255 && gc2[3] == 255 ||
gc[0] == 255 && gc[1] == 255 && gc[2] == 0 && gc[3] == 255 ||
gc2[0] == 255 && gc2[1] == 255 && gc2[2] == 0 && gc2[3] == 255){
this.gravSpeed = this.dgrav;
this.isOnGround = true;
return;
}
else{
this.y += this.gravSpeed;
if(this.gravSpeed < this.tv){
this.gravSpeed += this.ac;
}
else{
this.gravSpeed = this.tv;
}
this.isOnGround = false;
}
}
Your main problem is in your gravity method, particularly this block of code:
if(gc[0] == 0 && gc[1] == 0 && gc[2] == 255 && gc[3] == 255 ||
this.y >= 400 - this.scale ||
gc2[0] == 0 && gc2[1] == 0 && gc2[2] == 255 && gc2[3] == 255 ||
gc[0] == 255 && gc[1] == 255 && gc[2] == 0 && gc[3] == 255 ||
gc2[0] == 255 && gc2[1] == 255 && gc2[2] == 0 && gc2[3] == 255){
this.gravSpeed = this.dgrav;
this.isOnGround = true;
return;
}
This evaluates irrespective of whether the player is actually on the ground, which results in the issue where the player is getting stuck on the right-hand block.
A potential way to solve it is with actually using code you already have tucked within that condition:
if (this.y >= height - this.scale) {
this.y = height - this.scale; // ensure the player's height is properly constrained
this.gravSpeed = this.dgrav;
this.isOnGround = true;
}
This prevents the sticking as it doesn't set the player variable isOnGround = true when it's not.
Here's a working example:
class player {
constructor(x, y, scale, grav, ac, speed) {
this.x = x;
this.y = y;
this.dtime = 20;
this.jumpTimer = 20;
this.jumpLimit = 12;
this.jumpedHeight = 0;
this.jumping = false;
this.wallR = false;
this.wallL = false;
this.moveR = false;
this.moveL = false;
this.tv = 10;
this.dgrav = grav;
this.ac = ac;
this.speed = speed;
this.gravSpeed = grav;
this.canGravity = true;
this.isOnGround = false;
this.scale = scale;
}
draw() {
fill("red");
rect(this.x, this.y, this.scale, this.scale);
}
gravity() {
let gc = get(this.x, this.y + 21);
let gc2 = get(this.x + this.scale, this.y + 21);
if (this.y >= height - this.scale) {
this.y = height - this.scale;
this.gravSpeed = this.dgrav;
this.isOnGround = true;
} else {
this.y += this.gravSpeed;
if (this.gravSpeed < this.tv) {
this.gravSpeed += this.ac;
} else {
this.gravSpeed = this.tv;
}
this.isOnGround = false;
}
}
move() {
let wallcheckL = get(this.x - 1, this.y);
let wallcheckR = get(this.x + this.scale + 2, this.y);
let wallcheckLB = get(this.x - 1, this.y + this.scale - 5);
let wallcheckRB = get(this.x + this.scale + 2, this.y + this.scale - 5);
if (
(wallcheckL[0] == 0 && wallcheckL[1] == 0 && wallcheckL[2] == 255) ||
this.x == 0 ||
(wallcheckLB[0] == 0 && wallcheckLB[1] == 0 && wallcheckLB[2] == 255) ||
(wallcheckL[0] == 0 && wallcheckL[1] == 128 && wallcheckL[2] == 0)
) {
this.wallL = true;
} else {
this.wallL = false;
}
if (
(wallcheckR[0] == 0 && wallcheckR[1] == 0 && wallcheckR[2] == 255) ||
this.x >= 400 - this.scale ||
(wallcheckRB[0] == 0 && wallcheckRB[1] == 0 && wallcheckRB[2] == 255) ||
(wallcheckR[0] == 0 && wallcheckR[1] == 128 && wallcheckR[2] == 0)
) {
this.wallR = true;
} else {
this.wallR = false;
}
if (this.moveR == true && this.wallR == false) {
this.x += this.speed;
} else if (this.moveL == true && this.wallL == false) {
this.x -= this.speed;
}
}
jump() {
let uc = get(this.x, this.y - 2);
let ucr = get(this.x + this.scale, this.y - 2);
if (
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 0 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 0
) {
this.y -= 5;
this.jumpedHeight += 1;
} else {
if (
(this.jumpedHeight < this.jumpLimit &&
this.isOnGround == true &&
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 255 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 255) ||
(this.jumpedHeight < this.jumpLimit &&
this.isOnGround == true &&
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 0 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 0) ||
(this.jumpedHeight < this.jumpLimit &&
this.isOnGround == true &&
uc[0] == 255 &&
uc[1] == 255 &&
uc[2] == 0 &&
ucr[0] == 255 &&
ucr[1] == 255 &&
ucr[2] == 255)
) {
this.y -= 5;
this.jumpedHeight += 1;
} else {
this.gravSpeed = this.dgrav;
this.jumping = false;
}
}
}
}
class ground{
constructor(x, y, color){
this.x = x;
this.color = color;
this.y = y;
}
draw(){
fill(this.color);
rect(this.x, this.y, 40, 40);
}
}
var groundArray = [];
groundArray[0] = [0];
groundArray[1] = [0];
groundArray[2] = [0];
groundArray[3] = [0];
groundArray[4] = [0];
groundArray[5] = [0];
groundArray[6] = [1,0,0,0,0,0,0,1];
groundArray[7] = [1,0,0,0,0,0,0,1];
groundArray[8] = [1,0,0,0,0,0,0,1];
groundArray[9] = [1,0,0,0,0,0,0,1];
function setup() {
noStroke();
createCanvas(400, 400);
for(let y = 0; y < groundArray.length; y++){
for(let x = 0; x < groundArray[y].length; x++){
if(groundArray[y][x] == 1){
groundArray[y][x] = new ground(x * 40, y * 40, "blue");
}
else if(groundArray[y][x] == 2){
groundArray[y][x] = new ground(x * 40, y * 40, "yellow");
}
else if(groundArray[y][x] == 3){
groundArray[y][x] = new ground(x * 40, y * 40, "green");
}
}
}
}
var play = new player(200, 0, 20, 3, 0.06, 4);
function draw() {
background(255);
for(let y = 0; y < groundArray.length; y++){
for(let x = 0; x < groundArray[y].length; x++){
if(groundArray[y][x] != 0){
groundArray[y][x].draw();
}
}
}
play.move();
if(play.jumping == true){
play.jump();
}
else{
play.gravity();
}
play.draw();
}
function keyPressed(){
if(keyCode == RIGHT_ARROW){
play.moveL = false;
play.moveR = true;
}
else if(keyCode == LEFT_ARROW){
play.moveR = false;
play.moveL = true;
}
if(keyCode == UP_ARROW){
play.jumping = true;
}
}
function keyReleased(){
if(keyCode == RIGHT_ARROW){
play.moveR = false;
}
if(keyCode == LEFT_ARROW){
play.moveL = false;
}
if(keyCode == UP_ARROW){
play.jumping = false;
play.gravSpeed = play.dgrav;
play.jumpedHeight = 0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
I have fixed my problem. i found that in my gravity script it was checking too far to the right where it would collide with the wall so i changed it to this and it now works
gravity(){
let gc = get(this.x, this.y + 21);
let gc2 = get(this.x + this.scale - 2, this.y + 21);
if(gc[0] == 0 && gc[1] == 0 && gc[2] == 255 && gc[3] == 255 ||
this.y >= 400 - this.scale ||
gc2[0] == 0 && gc2[1] == 0 && gc2[2] == 255 && gc2[3] == 255 ||
gc[0] == 255 && gc[1] == 255 && gc[2] == 0 && gc[3] == 255 ||
gc2[0] == 255 && gc2[1] == 255 && gc2[2] == 0 && gc2[3] == 255){
this.gravSpeed = this.dgrav;
this.isOnGround = true;
return;
}
else{
this.y += this.gravSpeed;
if(this.gravSpeed < this.tv){
this.gravSpeed += this.ac;
}
else{
this.gravSpeed = this.tv;
}
this.isOnGround = false;
}
}

Why do I get the Error: "Cannot read property 'style' of null" on line 216 because of something also on lines 190, 200, 213?

* I can't figure out why I get the following error on my console: "Cannot read property 'style' of null" on line 216(near the bottom, I have put a comment) because of something also on lines 190, 200, 213? I think the problem is about the laser variable... Please help. I would really appreciate if someone could help me as soon as possible.*
'''
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>test</title>
<div>
<h1 style="text-align:center; color:purple;" id="pixelator">
<big>
<i>
<b>
Pixelator
</b>
</i>
</big>
</h1>
<button type="button" id="button1" onclick="Instructions()">Instructions for game</button>
<button type="button" id="button2" onclick="YouTube()">YouTube</button>
<h3 id="Instructions1">
Use the keys WASD to controll player one(blue), Q to
shoot left and E to shoot right. Use the arrow keys to controll player two(),
1 on the numberpad to shoot left and two to shoot right.
</h3>
<button type="button" id="Close" onclick="close1()">Close</button>
</div>
<img src="C:/Users/Tania/Documents/Website/Screenshots/Nice.jpg" alt="Image not found" id="Pic">
</head>
<body style="background-color:green">
<style>
button {
background-color: #4169E1;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 30%;
height: 45px;
}
#hero {
background:#ff0000;
width:20px;
height:50px;
position:absolute;
}
#player {
background:#ff0000;
width:20px;
height:50px;
position:absolute;
}
#Pic {
width: 150px;
}
#laser {
width: 30;
height: 3;
background:#ff0000
position:absolute;
}
</style>
<div id="player"></div>
<div id="hero"></div>
<div id="laser"></div>
<script type="text/javascript">
function YouTube(){
window.open("https://www.youtube.com/channel/UCe9MhUIA6wwwchVBzypCBnA");
}
document.getElementById("Instructions1").style.display = "none";
document.getElementById("Close").style.display = "none";
function Instructions() {
document.getElementById("Instructions1").style.display = "block";
document.getElementById("Close").style.display = "block";
}
function close1() {
document.getElementById("Instructions1").style.display = "none";
document.getElementById("Close").style.display = "none";
}
var LEFT_KEY = 65;
var UP_KEY = 87;
var RIGHT_KEY = 68;
var DOWN_KEY = 83;
var LEFT_ARROW = 37;
var RIGHT_ARROW = 39;
var SPACE_KEY = 32;
var DOWN_ARROW = 40;
var UP_ARROW = 38;
var Q_KEY = 81;
var E_KEY = 69;
var HERO_MOVEMENT = 10;
var lastLoopRun = 0;
var controller = new Object();
var player = new Object();
player.element = 'player'
player.x = 650;
player.y =460;
var hero = new Object();
hero.element = 'hero';
hero.x = 250;
hero.y = 460;
var laser = new Object();
laser.x = 0;
laser.y = -120;
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 1910) {
sprite.x = 1910 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 940) {
sprite.y = 940 - sprite.h;
}
}
function createSprite(element, x, y, w, h) {
var result=new Object();
result.element=element;
result.x=x;
result.y=y;
result.w=w;
result.h=h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
if (keyCode == LEFT_ARROW) {
controller.leftarrow = isPressed;
}
if (keyCode == RIGHT_ARROW) {
controller.rightarrow = isPressed;
}
if (keyCode == UP_ARROW) {
controller.rightarrow = isPressed
}
if (keyCode == DOWN_ARROW) {
controller.downarrow = isPressed
}
if (keyCode == Q_KEY) {
controller.qkey = isPressed
}
if (keyCode == E_KEY) {
controller.ekey = isPressed
}
}
function handleControls() {
if (controller.down) {
hero.y += HERO_MOVEMENT
}
if (controller.up) {
hero.y -= HERO_MOVEMENT
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.qkey && laser.x <= -120) {
laser.x=hero.x-20;
laser.y=hero.y+15;
}
if (controller.ekey && laser.x <= -120) {
laser.x=hero.x+20;
laser.y=hero.y+10;
}
ensureBounds(hero);
}
function showSprites() {
setPosition(hero);
setPosition(laser);
setPosition(player)
}
function updatePositions() {
laser.x-= 90
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
showSprites();
lastLoopRun = new Date().getTime();
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
loop();
function setPosition(sprite) {
var e = document.getElementById(sprite.element)
//***LINE 216-*** e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
createSprite('laser', 0, -120, 2, 50)
</script>
</body>
</html>
'''
Your laser object doesn't have the laser.element property set, if you add laser.element='laser'; after the laster.x and laser.y inicializations (line 104) this error should be fixed

Laser does not shoot after I added a player

I've been trying to make a game where a character shoots a laser, but for some reason when you press Q, which is the firing key, the laser doesn't shoot, which is weird because I have tried this code before and it worked, the only thing I changed is I have added another player to the game, and it doesn't give me any error messages
'''
#hero {
background: #ff0000;
width: 20px;
height: 50px;
position: absolute;
}
#player {
background: #ff0000;
width: 20px;
height: 50px;
position: absolute;
}
#Pic {
width: 150px;
}
#laser {
width: 30;
height: 3;
background: #ff0000 position:absolute;
}
#plaser {
width: 30;
height: 3;
background: #ff0000 position:absolute;
}
</style>
<div id="player"></div>
<div id="hero"></div>
<div id="laser"></div>
<div id="plaser"></div>
<script type="text/javascript">
var LEFT_KEY = 65;
var UP_KEY = 87;
var RIGHT_KEY = 68;
var DOWN_KEY = 83;
var LEFT_ARROW = 37;
var RIGHT_ARROW = 39;
var SPACE_KEY = 32;
var DOWN_ARROW = 40;
var UP_ARROW = 38;
var Q_KEY = 81;
var E_KEY = 69;
var HERO_MOVEMENT = 10;
var ONE_KEY = 97;
var TWO_KEY = 98;
var lastLoopRun = 0;
var controller = new Object();
var player = new Object();
player.element = 'player'
player.x = 1450;
player.y = 460;
var hero = new Object();
hero.element = 'hero';
hero.x = 250;
hero.y = 460;
var laser = new Object();
laser.element = 'laser'
laser.x = 0;
laser.y = -120;
laser.w = 30;
laser.h = 3;
var plaser = new Object();
plaser.element = 'plaser'
plaser.x = 0;
plaser.y = -130;
plaser.w = 30;
plaser.h = 3;
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 1910) {
sprite.x = 1910 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 940) {
sprite.y = 940 - sprite.h;
}
}
function createSprite(element, x, y, w, h) {
var result = new Object();
result.element = element;
result.x = x;
result.y = y;
result.w = w;
result.h = h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
if (keyCode == LEFT_ARROW) {
controller.leftarrow = isPressed;
}
if (keyCode == RIGHT_ARROW) {
controller.rightarrow = isPressed;
}
if (keyCode == UP_ARROW) {
controller.uparrow = isPressed
}
if (keyCode == DOWN_ARROW) {
controller.downarrow = isPressed
}
if (keyCode == Q_KEY) {
controller.qkey = isPressed
}
if (keyCode == E_KEY) {
controller.ekey = isPressed
}
if (keyCode == ONE_KEY) {
controller.onekey = isPressed
}
if (keyCode == TWO_KEY) {
controller.twokey = isPressed
}
}
function handleControls() {
if (controller.down) {
hero.y += HERO_MOVEMENT
}
if (controller.up) {
hero.y -= HERO_MOVEMENT
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.qkey && laser.x <= -120) {
laser.x = hero.x - 20;
laser.y = hero.y + 15;
}
if (controller.space && laser.x <= -120) {
laser.x = hero.x + 20;
laser.y = hero.y + 10;
}
if (controller.onekey && plaser.x <= -120) {
plaser.x = player.x - 20;
plaser.y = player.y + 15;
}
if (controller.twokey) {
}
if (controller.uparrow) {
player.y -= HERO_MOVEMENT
}
if (controller.downarrow) {
player.y += HERO_MOVEMENT
}
if (controller.leftarrow) {
player.x -= HERO_MOVEMENT;
}
if (controller.rightarrow) {
player.x += HERO_MOVEMENT;
}
ensureBounds(hero);
ensureBounds(player)
}
function showSprites() {
setPosition(hero);
setPosition(laser);
setPosition(player)
setPosition(plaser)
}
function updatePositions() {
laser.x -= 90
plaser.x -= 90
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
showSprites();
lastLoopRun = new Date().getTime();
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
loop();
function setPosition(sprite) {
var e = document.getElementById(sprite.element)
e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
createSprite('laser', 0, -120, 2, 50)
createSprite('plaser', 0, -120, 2, 50)
</script>
</body>
</html>
'''

how to get multiple keyboard inputs in javaScript

I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}

Categories

Resources