Using one function with different variables - javascript

Try to create two controllers with a same logic. when I use separate functions for each var it works. But when I try to pass var as parameter it does nothing.
Code here:
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num) {
$scope.num ++;
};
$scope.dist_btn = function(num) {
if ($scope.num > 0) {
$scope.num --;
} else {
$scope.num = 0;
}
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1)">-</button>
<button ng-click="add_btn(Score2">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2)">-</button>
</div>
</div>

You can use this logic without useing any array, you used $scope.num but it creates a new variable on the scope so fails. this would work properly
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num,from) {
num ++;
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
$scope.dist_btn = function(num,from ) {
if (num > 0) {
num --;
} else {
num = 0;
}
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1,1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1,1)">-</button>
<button ng-click="add_btn(Score2,2)">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2,2)">-</button>
</div>
</div>

Simple and dirty solution :)
There could be something better
function Ctrl($scope) {
$scope.Score = [0, 0];
$scope.add_btn = function(num) {
$scope.Score[num]++;
};
$scope.dist_btn = function(num) {
if ($scope.Score[num] > 0) {
$scope.Score[num]--;
} else {
num = 0;
}
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(0)">+</button>
<input type="text" value="{{Score[0]}}">
<button ng-click="dist_btn(0)">-</button>
<button ng-click="add_btn(1)">+</button>
<input type="text" value="{{Score[1]}}">
<button ng-click="dist_btn(1)">-</button>
</div>
</div>

$scope.num // find num inside #scope
$scope[num] // find the member inside scope variable with the value of num (Score1 in your case)
also send the parameter from the element like this:
<button ng-click="add_btn('Score1')">+</button>
and instead num please refactor to id or something.. in short:
$scope.add_btn = function(id)
{
$scope[id]++;
};

Related

Function that assigns new value appears to initially work the first time, but doesn't appear to return to beginning of if statement the second time

I am in the middle of the Pig Dice problem and I am trying to use the function switchPlayers() to switch between player1 and player2. When clicking "Roll Dice", it appears to switch to the second player but then no longer switches to the first player. After re-working it a few times, I'm starting to think the issue may be that even if Player2 updates to .isTurn = false the function is longer being called? I appreciate any pointers here (Note, haven't worked on the New Game or Hold Button yet)Thank you!
JSFiddle
//business logic for dice
function Dice() {
this.diceValue = 1;
this.roll = 0;
}
function Player() {
this.score = 0;
this.dice = new Dice()
this.isTurn = true
}
//global Players
player1 = new Player();
player2 = new Player();
function switchPlayers() {
if (player1.dice.roll === 0) {
player1.isTurn = false;
} else if (player2.dice.roll === 0) {
player2.isTurn = false;
}
}
Dice.prototype.rollDice = function() {
this.diceValue = Math.floor((Math.random() * 6) + 1);
if (this.diceValue === 1) {
this.roll = 0;
} else {
this.roll = this.diceValue;
}
}
Player.prototype.calcScore = function() {
this.dice.rollDice()
if (this.dice.roll === 0) {
switchPlayers();
} else {
this.score += this.dice.roll
}
}
//ui logic
$(document).ready(function() {
$("button.btn-roll").click(function(event) {
if (player1.isTurn !== false) {
player1.calcScore();
$('#p1-total').html(player1.score);
$('#p1-roll').html(player1.dice.roll);
} else if (player2.isTurn === true) {
player2.calcScore();
$('#p2-total').html(player2.score);
$('#p2-roll').html(player2.dice.roll)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.5.1.js"></script>
<script src="js/scripts.js"></script>
<title>Pig Dice!</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-1-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player1-score">
<p>this roll points: <span id="p1-roll"></span></p>
<p>
total: <span id="p1-total"></span>
</p>
</div>
</div>
</div>
<div class="player-2-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player1-score">
<p>this roll: <span id="p2-roll"></span></p>
<p>
total: <span id="p2-total"></span>
</p>
</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-checkmark"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<img src="img/die5.png" alt="Dice" class="dice die1">
</div>
</body>
</html>
Keeping your logic, i have reviewed your code, added some tips (button hold), so you could easily understant what i have done and increase yours skills:
function initGame(){
//selectRandomly wich players begins
idToPlay = Math.floor((Math.random()*maxNumberPlayers));
for(let p = 0;p < maxNumberPlayers;p++){
let id = '#p' + p;
$(id + '-action').html('');
$(id + '-name').text(players[p].name);
$(id + '-total').html(players[p].score);
$(id + '-roll').html('--');
$(id + '-round').html('--');
$(id + '-dice').html('--');
}
$('#p' + idToPlay + '-action').html('<b>** Its your turn! **</>');
}
//business logic for dice
function Dice() {
this.diceValue=1;
this.roll=0;
this.round=0;
}
function Player(name) {
this.name = name
this.score = 0;
players.push(this);
}
//global Players
players = [];
new Player("John");
new Player("Peter");
maxNumberPlayers = players.length;
dice = new Dice();
idToPlay = -1;//first player will be choosen by initGame
function switchPlayers() {
displayResult();
if(++idToPlay == maxNumberPlayers) idToPlay = 0;
dice.round = 0;
$( 'span[id$="-action"]').html('');
$('#p' + idToPlay + '-action').html('<b>** Its your turn! **</>');
}
Dice.prototype.rollDice = function() {
this.diceValue = Math.floor((Math.random()*6)+1);
if (this.diceValue === 1) {
this.roll = 0;
this.round = 0
} else {
this.roll = this.diceValue;
this.round += this.roll;
}
}
Player.prototype.calcScore = function(isHoldButton = false) {
dice.rollDice();
if (dice.roll === 0) {
dice.round = 0;
switchPlayers();
} else {
this.round += dice.roll;
displayResult();
}
}
function displayResult(){
let id = '#p' + idToPlay;
$(id + '-name').html(players[idToPlay].name);
$(id + '-total').html(players[idToPlay].score);
$(id + '-roll').html(dice.roll);
$(id + '-round').html(dice.round);
$(id + '-dice').html(dice.diceValue);
}
//ui logic
$(document).ready(function() {
initGame();
$("button.btn-roll").click(function() {
players[idToPlay].calcScore();
});
$("button.btn-hold").click(function() {
players[idToPlay].score += dice.round;
switchPlayers();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.5.1.js"></script>
<script src="js/scripts.js"></script>
<title>Pig Dice!</title>
</head>
<body>
<p>Rule: If you roll a 1, you will receive 0 roll points for the round and it will be the other player's turn.
</p>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name"><span id="p0-name">Player 1</span><span> </span><span id="p0-action"></span></div>
<div class="player0-score">
<p>Dice points:<span id="p0-dice"></span>
<span> </span>Roll points:<span id="p0-roll"></span>
<span> </span>Round points:<span id="p0-round"></span>
<span> </span>total:<span id="p0-total"></span>
</p>
</div>
</div>
<div class="player-1-panel">
<div class="player-name"><span id="p1-name">Player 1</span><span> </span><span id="p1-action"></span></div>
<div class="player1-score">
<p>Dice points:<span id="p1-dice"></span>
<span> </span>Roll points:<span id="p1-roll"></span>
<span> </span>Round points:<span id="p1-round"></span>
<span> </span>total:<span id="p1-total"></span>
</p>
</div>
</div>
<button class="btn-new"><i class="ion-ios-checkmark"></i>New game</button>
<button class="btn-roll"><i class="ion-ios-loop"></i>Roll dice</button>
<button class="btn-hold"><i class="ion-ios-download-outline"></i>Hold</button>
<img src="img/die5.png" alt="Dice" class="dice die1">
</div>
</body>
</html>

When I put removeEventListener in another conditional statement it doesn't work

I have tried to solve this problem for a week but I can't find any solutions.
When I put removeEventListener in the function MediaQuery3(z) it doesn't work.
I used MediaQuery to add an event for mobile phone users and removed it for desktop users.
let firstNumber=0;
let secondNumber = 0;
function MediaQuery3(z) {
let inputSearch = document.getElementById("input-search");
let searchBtn = document.getElementById("search-btn");
if (z.matches) {
if (firstNumber==0) {
searchBtn.addEventListener("click", clickSearch);
function clickSearch() {
if (inputSearch.style.display==="none") {
inputSearch.style.display="block";
} else{
inputSearch.style.display="none";
}
}
firstNumber=1;
secondNumber=0
}
} else{
if (secondNumber==0) {
searchBtn.removeEventListener("click", clickSearch);
inputSearch.style.display="block";
}
firstNumber=0;
secondNumber=1
}}
var z = window.matchMedia("(max-width: 430px)");
MediaQuery3(z);
z.addListener(MediaQuery3) ;
<!doctype html >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<body>
<nav class="navbar navbar-expand-sm navbar-dark">
<img src="d82a392b-6975-49e1-a8fd-a6e28a195b2b_200x200.png" alt="logo" id="logo-image">
<form class="form-inline" >
<button id="search-btn" type="button" ><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAABD0lEQVRIie2UPW7CQBCFP5IS0gEnoQdyAxAHSQoUUSD+Gm4DIiegoITkAOEMJIQWTDFvwY3xrqFAUZ402rX95r2xvTPwV1EGRsAHsFOsgCFQula8BWyBKCF+gOY14gcJTYAqkFfUgKme7YFGqHg5Vnn7Au9NnG+gGGIw4lx5GmbiDkIMPpVU9eDWxV2FGPwqqeDBfRJ3m0Z8iO2jgGJyvsS4wVprxSPPcb5CDN61vngYvGqdeXBPKGFNFGFHMQkdcTZk6Oom1kSRqqtjP70APGNv6Tq6Gyru0MCaKGlUbCTurvtZTIpYEy2x47vTfsD5s8RNM5mkwY0MF+N/k7sy6bmbjzc0WGAzak7gGL9vHAG+Ol6n6x8u5AAAAABJRU5ErkJggg=="/></button>
<input id="input-search" class="form-control" type="text" placeholder="" aria-label="Search">
</form>
<img src="https://img.icons8.com/pastel-glyph/64/000000/shopping-cart--v1.png" id="cart">
</nav>
</body>
</html>
The listener you add with addEventListener has to be the exact same reference to the exact same function that you give to removeEventListener. But since you've defined clickSearch as a nested function, it is actually given a different reference every time MediaQuery3 is executed, because each one is bound to a different closure. If you move clickSearch outside of the function so it's not nested, the reference will be the same both times and it'll work properly.
let firstNumber = 0;
let secondNumber = 0;
function clickSearch() {
let inputSearch = document.getElementById("input-search");
if (inputSearch.style.display === "none") {
inputSearch.style.display = "block";
} else {
inputSearch.style.display = "none";
}
}
function MediaQuery3(z) {
let inputSearch = document.getElementById("input-search");
let searchBtn = document.getElementById("search-btn");
if (z.matches) {
if (firstNumber == 0) {
searchBtn.addEventListener("click", clickSearch);
firstNumber = 1;
secondNumber = 0;
}
} else {
if (secondNumber == 0) {
searchBtn.removeEventListener("click", clickSearch);
inputSearch.style.display = "block";
}
firstNumber = 0;
secondNumber = 1;
}
}
var z = window.matchMedia("(max-width: 430px)");
MediaQuery3(z);
z.addListener(MediaQuery3);
<!doctype html >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<body>
<nav class="navbar navbar-expand-sm navbar-dark">
<img src="d82a392b-6975-49e1-a8fd-a6e28a195b2b_200x200.png" alt="logo" id="logo-image">
<form class="form-inline" >
<button id="search-btn" type="button" ><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAABD0lEQVRIie2UPW7CQBCFP5IS0gEnoQdyAxAHSQoUUSD+Gm4DIiegoITkAOEMJIQWTDFvwY3xrqFAUZ402rX95r2xvTPwV1EGRsAHsFOsgCFQula8BWyBKCF+gOY14gcJTYAqkFfUgKme7YFGqHg5Vnn7Au9NnG+gGGIw4lx5GmbiDkIMPpVU9eDWxV2FGPwqqeDBfRJ3m0Z8iO2jgGJyvsS4wVprxSPPcb5CDN61vngYvGqdeXBPKGFNFGFHMQkdcTZk6Oom1kSRqqtjP70APGNv6Tq6Gyru0MCaKGlUbCTurvtZTIpYEy2x47vTfsD5s8RNM5mkwY0MF+N/k7sy6bmbjzc0WGAzak7gGL9vHAG+Ol6n6x8u5AAAAABJRU5ErkJggg=="/></button>
<input id="input-search" class="form-control" type="text" placeholder="" aria-label="Search">
</form>
<img src="https://img.icons8.com/pastel-glyph/64/000000/shopping-cart--v1.png" id="cart">
</nav>
</body>
</html>

Move div with keys

I have to create a little program in AngularJS for my school, but I'm not very advanced yet, because I lack basic training.
I tried to make a texture move using arrow keys, but I didn't have any success finding a usable answer on the Internet.
I'd be happy if anyone would help me.
Here is the code I use for now to move it, if that helps:
<!DOCTYPE html>
<html>
<head>
<title>Angular Game</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body bgcolor="#151B54">
<div ng-app="myApp" ng-controller="myCtrl">
<div id="myDiv" ng-style=" {'position':'relative','height':'20px','width':'92px','background-color':'#348781','left': divleft+'px','top':divtop+'px'}">Raumschiff</div>
<input type="button" ng-mousedown="goLeft()" value="<"> <input type="button" ng-mousedown="goRight()" value=">"><br>
<input type="button" ng-mousedown="goDown()" value="v"> <input type="button" ng-mousedown="goUp()" value="^">
<input type="button" ng-click="startInterval()" value="start">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$interval) {
$scope.divleft = 200;
$scope.divtop = 300;
$scope.goRight = function ()
{
$scope.divvel2 +=1;
}
$scope.goLeft = function ()
{
$scope.divvel2 -=1;
}
$scope.goUp = function ()
{
$scope.divvel +=1;
}
$scope.goDown = function ()
{
$scope.divvel -=1;
}
$scope.moveDiv = true;
var intervalHandler;
$scope.divvel ="0";
$scope.divvel2 ="0";
$scope.startInterval = function ()
{
$interval.cancel(intervalHandler);
intervalHandler = $interval(myIntervalFunction,50);
}
myIntervalFunction = function()
{
$scope.divtop-=parseInt($scope.divvel);
$scope.divleft+=parseInt($scope.divvel2);
}
});
</script>
</body>
</html>
To make a texture move using arrow keys. Try this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$interval) {
$scope.divleft = 100;
$scope.divtop = 30;
$scope.goRight = function ()
{
$scope.divleft +=1;
}
$scope.goLeft = function ()
{
$scope.divleft -=1;
}
$scope.goUp = function ()
{
$scope.divtop -=1;
}
$scope.goDown = function ()
{
$scope.divtop +=1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div id="myDiv" ng-style=" {'position':'relative','height':'20px','width':'92px','background-color':'#348781','left': divleft+'px','top':divtop+'px'}">Raumschiff</div>
<input type="button" ng-mousedown="goLeft()" value="<"> <input type="button" ng-mousedown="goRight()" value=">"><br>
<input type="button" ng-mousedown="goDown()" value="v"> <input type="button" ng-mousedown="goUp()" value="^">
</div>
Angular has directives that will allow you to easily listen for key events.
I think ng-keyup should work fine for you.
You will need to add the ng-keyup directive to the body tag to make sure you listen for key events at the highest level. You will also have to move your ng-app and ng-controller directives to the body tag too so that the function that you declare for your key events is in the correct scope.
So change
<body bgcolor="#151B54">
<div ng-app="myApp" ng-controller="myCtrl">
to
<body bgcolor="#151B54" ng-app="myApp" ng-controller="myCtrl" ng-keyup="handleKeyup($event)">
<div>
You will then be able to do something with those events in your controller.
So add this to your controller:
$scope.handleKeyup = function (e) {
switch (e.which) {
case 37:
$scope.goLeft();
break;
case 38:
$scope.goUp();
break;
case 39:
$scope.goRight();
break;
case 40:
$scope.goDown();
break;
}
};

Javascript event handler is not working

I am trying to to increment/decrement a value in a paragraph when a button is clicked.
$(document).ready(function() {
var breakTime = 5;
var section = 25;
var start = "Start";
var stop = "Stop";
function Pomodoro(element, target) {
this.element = element;
this.target = target;
};
Pomodoro.prototype.incrementer = function incrementer() {
// this takes care of break and section timers incrementing
this.element.click(function() {
breakTime++;
var el = this.target;
el.html(breakTime);
});
};
// end
Pomodoro.prototype.decrementer = function decrementer() {
// this takes care of break and section timers incrementing
breakerDec.element.click(function() {
breakTime--;
var el = breakerDec.target.html(breakTime);
});
};
// end
var breakerInc = new Pomodoro();
var ele = $("#inner1");
var tar = $("#par");
breakerInc.element = ele;
breakerInc.target = tar;
breakerInc.incrementer.bind(breakerInc);
//end
var breakerDec = new Pomodoro();
breakerDec.element = $("#inner2");
breakerDec.target = $("#par");
breakerDec.decrementer();
var sectionInc = new Pomodoro($("#inner3"), $("#par2"));
sectionInc.incrementer.bind(sectionInc);
});
and i am getting no result when i click the button.
this is the html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pomodoro Timer</title><!-- End of Title -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="wrapper">
<div class="top">
<div class="div div-1"><p id="par" class="breaktime-1">5</p>
<div class="inner-div inner-1"><button id="inner1" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner2" type="button" class="btn">-</button></div>
</div>
<div class="div div-2"><p id="par2" class="breaktime">25</p>
<div class="inner-div inner-1"><button id="inner3" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner4" type="button" class="btn">-</button></div>
</div>
</div>
<div class="div div-3">
<h3 class="heading">section</h3>
<button type="button" class="btn-Start-Stop"></button
</div>
<div><p></p></div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Here is one (trimmed-down) solution just using vanilla javascript:
function changeValue() {
var breaktime = this.parentNode.getElementsByClassName('breaktime')[0];
var val = breaktime.innerHTML;
if (this.className === 'increment') {
val++;
}
else if (this.className === 'decrement') {
val--;
}
breaktime.innerHTML = val;
}
function startStop() {
var values = [];
var breaktimes = document.getElementsByClassName('breaktime');
breaktimes[1].classList.toggle('decrementing');
if (breaktimes[1].classList.contains('decrementing') === true) {
values[1] = parseInt(breaktimes[1].innerHTML);
values[1]--;
breaktimes[1].innerHTML = values[1];
var decrementer = setInterval(function(){
values[0] = parseInt(breaktimes[0].innerHTML);
values[1] = parseInt(breaktimes[1].innerHTML);
if (breaktimes[1].classList.contains('decrementing') !== true) {
clearInterval(decrementer);
}
values[1]--;
breaktimes[1].innerHTML = values[1];
if (values[1] === values[0]) {
window.alert('The counter has reached ' + values[1]);
clearInterval(decrementer);
}
}, 1000);
}
}
var buttons = document.getElementsByTagName('button');
var startStopButton = buttons[(buttons.length -1)];
for (var i = 0; (i+1) < buttons.length; i++) {
buttons[i].addEventListener('click',changeValue,false);
}
startStopButton.addEventListener('click',startStop,false);
<section>
<div>
<p class="breaktime">5</p>
<button id="inner1" type="button" class="increment">+</button>
<button id="inner2" type="button" class="decrement">-</button>
</div>
<div>
<p class="breaktime">25</p>
<button id="inner3" type="button" class="increment">+</button>
<button id="inner4" type="button" class="decrement">-</button>
</div>
<div>
<h3>Section</h3>
<button type="button" class="btn-Start-Stop">Start / Stop</button>
</div>
<div>
<p></p>
</div>
</section>
If you'd like to implement logic using constructors, you can bind events inside of initialization of your instance.
Here is reworked your code based on your html. But code could be improved, so Pomodoro instance can be able not only to decrease or increase, but do both functions.
Also some template engine can give you ability to easy define amount of increase/decrease blocks you want to add to your page.

Javascript Help - Timer (Not Counting Up) and Alert Box (Not Showing Up)

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>

Categories