<!DOCTYPE html>
<html>
<head>
<title> Cookie Clicker! </title>
<script type="text/javascript">
var logAt=function(id,message){
document.getElementById(id).innerHTML=message;
};
</script>
</head>
<body>
<h1 class="center" style="text-align:center"> Cookie Clicker </h1>
<p class="center" id="para1" style="text-align:center;"> Keep collecting cookies and start your very own sweet empire!</p>
<p>
<div class="center" id="cookiesPerSecond" style="text-align:center"> </div>
<button id="getACookie" type="button" onClick="getCookie()"><image src="http://blog.speekee.com/wp-content/uploads/2014/09/Cookie.gif"
style="width:300px;height:300px;align:middle"></button>
<h3 id="cookies" style="text-align:center;">Cookies:0 </h3>
</p>
<h2 id="store"> Store</h2>
<p>
<button type="button" onClick="getOven()"> Buy another oven! <image
src="http://products.geappliances.com/MarketingObjectRetrieval/Dispatcher?RequestType=Image&Name=0107108.jpg" style="width:50px;height:50px"> </button>
</p>
<div id="oven"> <strong> 90 Cookies </strong> An extra oven <br> will give you half a cookie <br> per second</div>
<style>
#getACookie{
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
<script type="text/javascript">
var cookies=0;
var cookiesPerSecond=0;
function getCookie(){
cookies+=1;
logAt("cookies","Cookies:"+cookies);
};
var getOven=function(){
if(cookies>=10){
cookies=cookies-90
cookiesPerSecond+=0.5;
logAt("cookiesPerSecond","Cookies per second:"+cookiesPerSecond);
setInterval(function(){
cookies+=cookiesPerSecond;
logAt("cookies","Cookies:"+cookies);},1000);
}
else{
alert("You do not have enough cookies!");
}
};
</script>
</body>
</html>
When getting an oven more than once, (in the "getOven" function) instead of one cookie per second, it adds 2 cookies persecond, and so on. Is this a problem with my variables? What should i do to fix it?
You need to clear the previous intervals before starting a new one. See a modified code example below:
var cookies=0;
var cookiesPerSecond=0;
var interval = null; //Declare a variable to hold a reference to the interval
function getCookie(){
cookies+=1;
logAt("cookies","Cookies:"+cookies);
};
var getOven=function(){
if(cookies>=10){
cookies=cookies-90
cookiesPerSecond+=0.5;
logAt("cookiesPerSecond","Cookies per second:"+cookiesPerSecond);
// Check if a previous interval has been set, if so clear it.
if (interval != null) {
clearInterval(interval);
}
// Finally, set a new interval and store a reference to it in the variable
interval = setInterval(function(){
cookies+=cookiesPerSecond;
logAt("cookies","Cookies:"+cookies);},1000);
}
else{
alert("You do not have enough cookies!");
}
};
Related
I'm trying to use a single button to toggle between an image being visible and invisible. I want the first click to make the image appear, and the second to hide it again. I figured using a boolean would be the best way to do this, but I can't quite get it to work.
function myStats(){
counter = true;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
I realize this will obviously not work because I'm not toggling the boolean, but that's what I'm looking for help with.
Create a css class called hidden, then use classList.toggle(). When the button is clicked toggle the class on the image.
It can be done like this:
document.querySelector('button').addEventListener('click', myStats)
function myStats() {
document.getElementById('stat').classList.toggle('hidden')
}
.hidden { display: none; }
<center><button>Player 1</button></center>
<center><img id="stat" src="https://via.placeholder.com/150" class="hidden"></center>
I edited your snippet to put a toggle on there and made it so the function myStats() doesn't set counter = true everytime you click it. Seems to work fine. I also hoisted the declaration of the counter variable above that function declaration, since that's where your toggle should be, represented by counter = !counter.
let counter = true;
function myStats(){
counter = !counter;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
Boolean variable should be outside of the function so its value won't reset every time you called a function. Also you should toggle this boolean variable value from true to false and vise versa. Check out my solution. Hope this helps!
var isImageShouldBeVisible = true;
function toggleImageVisibility() {
isImageShouldBeVisible = !isImageShouldBeVisible;
if (isImageShouldBeVisible) {
document.getElementById('stat').style.display = 'block';
} else {
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:block;"/></center>
<button onclick="toggleImageVisibility()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
This is because counter remains same throughout the code. You need to add counter = !counter at end of you function. I would do it using ternary operators. There is need of Boolean just check the style.display
let elm = document.getElementById('stat');
function myStats(){
let {display} = elm.style;
elm.style.display = display === 'none' ? 'block' : 'none';
}
body{background-color: #A9A9A9;}
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
I have this small script. My probme is that when I click the Start button the count starts normally, but if I click it again, the counter starts acting weird. How do I avoid this issue and start a fresh counter on every button click?
$(".c1").click(function(e){
let a = 0;
setInterval(function(){ $("#timer").text(a); a++; }, 500);
})
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
The "acting weird" is because you're starting a second, separate timer, so now both are running, each putting its own copy of a in the element. You need to remember the previous timer's handle (the return value of setInterval) and cancel it (via clearInterval):
let handle = 0;
$(".c1").click(function(e) {
let a = 0;
clearInterval(handle)
handle = setInterval(function() {
$("#timer").text(a);
a++;
}, 500);
})
.card {
font-size: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
Note I've used the value 0 as the initial value of handle and then I've happily called clearInterval whether the timer was already running or not. 0 is an invalid handle value, and clearInterval (and clearTimeout) ignore invalid handle values, so you can safely do that. But add the if if you like.
You should reset your interval before starting the new one
let interval;
$(".c1").click(function(e) {
let a = 0;
if(interval) clearTimeout(interval);
interval = setInterval(function(){ $("#timer").text(a); a++; }, 500);
})
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
You have to clear the interval before starting a new one. Else, two things (or more) are incrementing a.
To clear an interval, just call clearInterval on the result of setInterval.
let interval;
$(".c1").click(function(e){
let a = 0;
clearInterval(interval);
interval = setInterval(function(){ $("#timer").text(a); a++; }, 500);
});
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer</div>
<br>
<br>
<span id="timer" class="card">0</span>
every time you click you start another one setInterval
solution
when it has to count from the beginning - use clearInterval
https://stackoverflow.com/a/5978560/3046335
to disable actions if we want to start the counter once - use .attr("disabled", true);
//1
var time = 0
$(".c1").click(function(e){
clearInterval(time); // stop if runn interval
let a = 0;
time = setInterval(function(){ $("#timer").text(a); a++; }, 500);
})
//2
$(".c2").click(function(e){
let a = 0;
setInterval(function(){ $("#timer2").text(a); a++; }, 500);
$(".c2").attr("disabled", true);
})
.card{ font-size:25px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<div class="btn c1"> Start Timer 1</div>
<br>
<br>
<span id="timer" class="card">0</span>
<br>
<br>
<div class="btn c2"> Start Timer 2</div>
<br>
<br>
<span id="timer2" class="card">0</span>
I have the buttons made in HTML but i cant seem to set the difficulty of the AI which is the function ais. i want to be able to set difficulty by pressing the buttons and adding to the ais like "ais == ais + 2" How would i do that?
My Code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf- 8" />
<title>Connor's Pong Project</title>
<!-- Style Sheet -->
<link href="css/CC_FinalProject.css" type="text/css"rel="stylesheet"/>
<!-- JS -->
<script src="js/CC_FinalProject.js"></script>
<script src="js/modernizr.js"></script>
</head>
<body>
<div class="center-text">
<h1> Welcome to Pong 2.0!</h1>
</div>
<canvas id="gc" width="640" height="480" class="center-block">
Your browser doesn't support Canvas.
</canvas>
<!-- Buttons -->
<br>
<div class="center-text">
<!-- add button -->
<button type="button" id="aie">Easy</button>
<button type="button" id="aim">Medium</button>
<button type="button" id="aih">Hard</button>
<!-- add a remove circle button here -->
<!-- add a change all circles button here -->
</div>
<!-- ^ End Buttons -->
<!-- Rules -->
<div class="center-text">
<h2> How to Play <br>
-Use Mouse to move bar <br>
-Try and score against the AI!
</h2>
</div>
My JS
// Variables //
p1y=p2y=40;
pt=10;
ph=100;
bx=by=50;
bd=6;
xv=yv=4;
score1=score2=0;
ais=4;
// window loading all //
window.onload=function(){
canvas=document.getElementById('gc');
context=canvas.getContext('2d');
setInterval(update,1000/30);
canvas.addEventListener('mousemove', function(e){
p1y = e.clientY-ph/2;
})
}
// Reset Function //
function reset(){
console.log('reset called');
bx=canvas.width/2;
by=canvas.height/2;
xv=-xv;
yv=3;
//Update Function//
}
function update(){
bx+=xv;
by+=yv;
if(by<0 && yv<0){
yv=-yv;
}
if(by>canvas.height && yv>0){
yv=-yv;
}
if(bx<0){
if(by>p1y && by<p1y+ph){
xv=-xv;
dy=by-(p1y+ph/2);
yv = dy*0.3;
} else{
score2++;
reset();
}
}
if(bx>canvas.width){
if(by>p2y && by<p2y+ph){
xv=-xv;
dy=by-(p2y+ph/2);
yv = dy*0.3;
} else{
score1++;
reset();
}
}
if(p2y+ph/2<by){
p2y+=ais;
} else{
p2y-=ais;
}
// reset canvas
context.clearRect(0,0,canvas.width,canvas.height);
// background
context.fillStyle='black';
context.fillRect(0,0,canvas.width,canvas.height);
// paddles
context.fillStyle='white';
context.fillRect(0,p1y,pt,ph); // p1 paddle
context.fillRect(canvas.width-pt,p2y,pt,ph); // p2 paddle
context.fillRect(bx-bd/2,by-bd/2,bd,bd); // ball
// scores
context.fillText(score1,100,100);
context.fillText(score2,canvas.width-100,100);
}
Add a button with <button onclick="addDifficulty()">Add Difficulty</button>
Then in JavaScript:
function addDifficulty() {
ais += 2
}
Here is what the full code would look like:
var ais = 4
function myFunction(difficulty) {
ais = difficulty
document.getElementById("demo").innerHTML = ais;
}
<p>Click the button to trigger a function that will change the value of ais</p>
<button onclick="myFunction(6)">Click me</button>
<button onclick="myFunction(8)">Click me</button>
<button onclick="myFunction(4)">Click me</button>
<p id="demo"></p>
I am new to JavaScript and HTML but am slowly getting HTML but JavaScript I am struggling with. I am stuck on a problem that is having me have a counter start when I click the Start Quiz button. I am also having a problem with an Alert Box showing up when I click the Submit Answers button. I am not looking for someone to give me the answer but some guidance would be helpful.
<head>
<meta charset="UTF-8" />
<title>Trivia Quiz: Movies</title>
<script src="modernizr-1.5.js" type="text/javascript" ></script>
<link href="quiz.css" rel="stylesheet" type="text/css" />
<script src="functions.js" type="text/javascript" ></script>
<script type="text/javascript">
var seconds = "0";
var clockID;
</script>
<script type="text/javascript">
function runClock() {
seconds++;
document.getElementByID('quizclock')value=seconds;
}
</script>
<script type="text/javascript">
function startClock() {
showQuiz();
clockId=setInterval ("runClock()", 1000);
}
</script>
<script type="text/javascript">
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
window.alert("You have" + correctAns + "correct of 5 in" + timer + "seconds");
}
</script>
</head>
<body onload="resetQuiz()">
<form id="quiz" name="quiz" action="">
<header>
<img src="tlogo.png" alt="Online Trivia" />
<nav class="horizontal">
<ul>
<li>Top Scores</li>
<li>Submit a Quiz</li>
<li>Quiz Bowl</li>
<li>Your Account</li>
</ul>
</nav>
</header>
<nav class="vertical">
<h1>Categories</h1>
<ul>
<li>Arts</li>
<li>Books</li>
<li>Culture</li>
<li>Geography</li>
<li>History</li>
<li>Movies</li>
<li>Music</li>
<li>People</li>
<li>Random</li>
<li>Science</li>
<li>Sports</li>
<li>Television</li>
</ul>
</nav>
<section id="main">
<h1>Movie Trivia</h1>
<p>
All of our trivia quizzes are scored on the number of correct
answers and the time required to submit those answers.
</p>
<p>
To start the quiz, click the <b>Start Quiz</b> button below,
which will reveal the first page of quiz questions and start
the timer. When you have completed the questions, click
the <b>Submit Answers</b> button on the quiz form.
</p>
<aside>
<input name="quizclock" id="quizclock" value="0" />
<input id="start" type="button" value="Start Quiz" onclick="startClock()" />
<input id="stop" type="button" value="Submit Answers" onclick="stopClock()"/>
</aside>
</section>
</form>
</body>
The code that is provided is partial and I believe that is the only part of the code that is needed for the question. Thanks.
Reset Function as requested:
function resetQuiz() {
document.quiz.quizclock.value = 0;
for (i=0; i<document.quiz.elements.length; i++) document.quiz.elements[i].disabled=false;
document.quiz.stop.disabled = true;
}
You have two errors.
1. document.getElementByID('sth') should be document.getElementById('sth').
Notice the lowercase d at the end of Id.
2. You should put a . before value like this:
document.getElementById('quizclock').value = seconds;
This is all assuming that you have implemented startQuiz(), resetQuiz() and showQuiz() and they are working correctly.
Hope Helps;
Try to run the code snippet!
var Quiz = (function($) {
var updateView = function(timeElapsed) {
$('#result').html(timeElapsed);
};
function Quiz() {
updateView(this.timing);
}
Quiz.prototype.timing = 0;
Quiz.prototype.start = function() {
var self = this;
if(self._isCounting) {
return;
}
return this._interval = (function() {
self._isCounting = true;
var interval = window.setInterval(function() {
self.timing += 1;
updateView(self.timing);
}, 1000);
return interval;
})();
};
Quiz.prototype.stop = function() {
window.clearInterval(this._interval);
this._isCounting = false;
return this;
};
Quiz.factory = function() {
return new Quiz();
};
return Quiz;
})(window.jQuery);
window.jQuery(document).ready(function($) {
var historyQuiz = Quiz.factory();
historyQuiz.start();
var modalIsOpen = false;
$('#stop').click(historyQuiz.stop.bind(historyQuiz));
$('#resume').click(historyQuiz.start.bind(historyQuiz));
$('#submitQuizData').click(function(event) {
historyQuiz.stop();
return $.Deferred().resolve(historyQuiz.timing)
.then(function(val) {
return $('#quizResult').html(val + 's')
})
.then(function(element) { return element.fadeIn(); })
.then(function(element) { modalIsOpen = true; })
});
$('#quizResult').click(function() {
if(modalIsOpen) { modalIsOpen = false; return $('#quizResult').fadeOut(); }
});
});
.quiz-result {
display: none;
text-align: center;
width: 300px;
height: 300px;
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button id="stop">STOP QUIZ</button>
<button id="resume">RESUME QUIZ</button>
<button id="submitQuizData">SUBMIT QUIZ DATA</button>
<div id="quizResult" class="quiz-result"></div>
Using Javascript, I want to toggle on and off between 2 images.
So far I am using a counter and then changing my innerHTML based off if the counter is even or odd for when the image is clicked
It works the first time i click the image by replacing the image already there, but after the first time it keeps on adding images instead.
How can i make it change the image after the second time rather than add images when I click?
<!DOCTYPE html>
<html>
<head>
<script>
var x = 0;
function myFunction() {
x++;
var div1 = document.getElementById('div1');
if (x % 2 != 0) {
var y = document.write('<img src="http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng" alt="sometext" onclick=myFunction()>');
div1.appendChild.innerHtml = y;
} else if (x % 2 == 0) {
var y = document.write('<img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text" onclick=myFunction()>')
div1.appendChild.innerHTML = y;
}
}
</script>
</head>
<body>
<div id="div1" style="font-size:12px" onclick=myFunction()> <span onclick=myFunction()>
<img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
</span>
</div>
</body>
</html>
If you are only trying to achieve the toggle effect something like this should work:
<!DOCTYPE html>
<html>
<head>
<script>
var x=0;
function myFunction(){
var div1=document.getElementById('div1');
if(x==0){
x=1;
document.getElementById("myimgid").src = "http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng";
}
else{
x=0;
document.getElementById("myimgid").src = "http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg";
}
}
</script>
</head>
<body>
<div id="div1" style="font-size:12px" onclick=myFunction()>
<span>
<img id="myimgid" src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
</span>
</div>
</body>
</html>