vertical bar chart with validation - javascript

I changed my code abit, because i want some validation inside my code. before the the bars had the "%" on it and the name typed in under the bar, now if i type in 2 participants, it creates 4 bars instead of 2. At the place where the names should be is an "undefined" and where the % should be is NaN%. Does someone know where the mistake is?
<head>
<title>examAnalysis</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
div {
float: left; margin-right: 10px;
}
div p {
text-align: center;
}
</style>
<script type="text/javascript">
var participant = [];
var maxPoints = 200;
var barWidth = 50;
function gatherData() {
var name;
var points;
while (name = window.prompt('Please enter the name of the participant:')) {
name = name.replace(/\s+/g, '')
if ((/[^A-Z\s\-\']/gi.test(name)) || (name == '')) {
alert ('You must enter a valid name! ');
} else {
participant.push({name: name});
while(points = window.prompt('Please enter the achieved points of the participant:')) {
points = parseInt(points, 10);
if ((/[^0-9\s\-\']/gi.test(points)) || (points == '')) {
alert ('You must enter a valid number! ');
} else {
participant.push({points: points});
break;
}
}
}
}
createChart();
};
function createChart ()
{
var i = 0;
var len = participant.length;
var bar = null;
var container = document.getElementById('chart');
container.innerHTML='';
while (i < len)
{
bar = document.createElement('div');
bar.style.width = barWidth + 'px';
bar.style.backgroundColor = getRandomColor();
bar.style.float = 'left';
bar.style.marginRight = '10px';
bar.style.height = ((participant[i].points / maxPoints) * 200) + 'px';
bar.style.marginTop = 200 - parseInt(bar.style.height) + 'px';
percent = ((participant[i].points / maxPoints) * 100) + '%';
bar.innerHTML = ['<p style="margin-top: ' + (parseInt(bar.style.height) - 17) + 'px">', percent, '<br />', participant[i].name, '</p>'].join('');
container.appendChild(bar);
i = i + 1;
}
};
function getRandomColor () {
return ['rgb(', Math.floor(Math.random() * 255), ', ', Math.floor(Math.random() * 255), ', ', Math.floor(Math.random() * 255), ')'].join('');
};
</script>
</head>
<body>
<button onclick="gatherData()">Add Participant</button>
<h4>Chart</h4>
<div id="chart"></div>
</body>

Try this:
function gatherData()
{
var name = window.prompt('Please enter the name of the participant:');
name = name.replace(/\s+/g, '');
if ((/[^A-Z\s\-\']/gi.test(name)) || (name == '') || (name == 'undefined'))
{
alert ('You must enter a valid name! ');
return;
}
var points = window.prompt('Please enter the achieved points of the participant:');
points = parseInt(points, 10);
if ((/[^0-9\s\-\']/gi.test(points)) || (points == ''))
{
alert ('You must enter a valid number! ');
return;
}
participant.push({name: name, points: points});
createChart();
};

Related

Why does Javascript give me a uncaught type null error?

I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this
"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
at init (payment.js:182)".
Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType;
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html";
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = validate;
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking;
}
window.onload = init;
It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.
make sure your <script> tag is in the last before the </body> tag. like below
<html>
<head>
</head>
<body>
<form>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
but not like this
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
</form>
</body>
</html>

How to change if "O" has put chess man then it is turn X put chess man and check winner of array 2D in OOP javascript?

This is function control Table.
/**
* #constructor
* #param {Number} width - dimension width for table
* #param {Number} height - dimension height for table
*/
function Table(width, height) {
this.table = [];
for (var x = 0; x < height; x++) {
this.table[x] = [];
for (var y = 0; y < width; y++) {
this.table[x][y] = ' ';
}
}
console.log('test', this.table);
this.width = width;
this.height = height;
}
Table.prototype = {
/**
* Representation for get width of table
*/
getWidth: function () {
return this.width;
},
/**
* Representation for get height of table
*/
getHeight: function () {
return this.height;
},
/**
* Representation for get table
*/
getTable: function () {
var x = new Array(this.getHeight());
for (var i = 0; i < this.getHeight(); i++) {
x[i] = new Array(this.getWidth());
};
},
/**
* Representation for set position of table
*/
setPosition: function (x, y, ch) {
this.table[x][y] = ch;
},
/**
* Representation for get value detail at cell of table
*/
getValueAt: function (x, y) {
return this.table[x][y];
},
/**
* Representation for check empty conditional
*/
isEmptyAt: function (x, y) {
return !this.table[x][y];
},
};
/**
* #constructor
* #param {String} character - X or O
*/
function Player(name, ch) {
this.name = name;
this.ch = ch;
}
var Printer = function () {
};
This is the function print to console .
Printer.prototype = {
/**
* Representation print table
*/
printTable: function (table) {
var str = '';
for (var i = 0; i < table.width; i++) {
var x = i;
for (var j = 0; j < table.height; j++) {
var y = j;
str += ' ' + table.getValueAt(x, y) + ' |';
}
str += '\n------------\n';
}
console.log(str);
},
/**
* Representation check winner conditional
*/
printWinner: function (player) {
},
};
/**
* #param newTable [array] : The array two-direction table
* #param player [object] : the object contain player X and O
*/
var GamePlay = function (table, playerOne, playerTwo) {
this.table = table;
this.playerOne = playerOne;
this.playerTwo = playerTwo;
this.printer = new Printer();
};
The GamePlay Control Table and Player.
GamePlay.prototype = {
run: function () {
console.log('Game start ...!');
var x = Math.floor(Math.random() * 3);
var y = Math.floor(Math.random() * 3);
this.putChessman(x, y, this.playerOne.ch);
this.printer.printTable(this.table);
if (ch === 'O') {
this.putChessman(x, y, this.playerTwo.ch);
} else {
this.putChessman(x, y, this.playerOne.ch);
}
},
This is CheckWin .
/**
* #param player [keywork] : the keywork X and O
*/
checkWin: function (table) {
var winner = 0;
//check each row for a winner
if(table[0][0] == table[0][1] && table[0][0] == table[0][2] && table[0][0] != 0) {
winner = table[0][0];
}
// check row 2 for winner
if (table[1][0] == table[1][1] && table[1][0] == table[1][2] && table[1][0] != 0 ){
winner = table[1][0];
}
// check row 3 for winner
if (table[2][0] == table[2][1] && table[2][0] == table[2][2] && table[2][0] != 0 ){
winner = table[2][0];
};
// check column 1 for winner
if (table[0][0] == table[1][0] && table[0][0] == table[2][0] && table[0][0] != 0 ){
winner = table[0][0];
}
// check column 2 for winner
if (table[0][1] == table[1][1] && table[0][1] == table[2][1] && table[0][1] != 0 ){
winner = table[0][1];
}
// check column 3 for winner
if (table[0][2] == table[1][2] && table[0][2] == table[2][2] && table[0][2] != 0 ){
winner = table[0][2];
}
//check each diagnoal for a winner
if (table[0][0] == table[1][1] && table[0][0] == table[2][2] && table[0][0] != 0 ){
winner = table[0][0];
}
// check second diagonal for winner
if (table[0][2] == table[1][1] && table[0][2] == table[2][0] && table[0][2] != 0 ){
winner = table[0][2];
}
return winner;
},
This is function put chess man . But it always turn else.
putChessman: function (x, y, ch) {
if (this.table.isEmptyAt(x, y) === true) {
console.log('# player ' + ch + ' put');
this.table.setPosition(x, y, ch);
if (ch === 'O') {
result = this.putChessman(x, y, this.playerTwo.ch);
if (result) {
ch = 'X';
}
} else {
result = this.putChessman(x, y, this.playerOne.ch);
if (result) {
ch = 'O';
}
}
} else {
console.log('# Other player already put on it');
}
},
};
var table = new Table(3, 3);
var playerOne = new Player('playerOne', 'O');
var playerTwo = new Player('playerTwo', 'X');
var game = new GamePlay(table, playerOne, playerTwo);
game.run();
At some point you need to set the variable "ch" to indicate what player needs to go. Right now you have this code in your main function:
if (ch === 'O') {
this.putChessman(x, y, this.playerTwo.ch);
} else {
this.putChessman(x, y, this.playerOne.ch);
}
One thing you could try doing is returning whether putChessman succeeded.
putChessman: function (x, y, ch) {
if (this.table.isEmptyAt(x, y) === true) {
console.log('# Other player already put on it');
return true; // CHANGED FROM THE CODE ABOVE
} else {
console.log('# player ' + ch + ' put');
this.table.setPosition(x, y, ch);
return false; // CHANGED FROM THE CODE ABOVE
}
You can capture the result in your main function, and use it to decide what "ch" should be.
if (ch === 'O') {
result = this.putChessman(x, y, this.playerTwo.ch);
if(result) {
ch = 'X';
}
} else {
result = this.putChessman(x, y, this.playerOne.ch);
if(result) {
ch = 'O';
}
}
Hope this helps!

Difficulty assigning a Discount

As the title says, I'm having trouble assigning discounts to my products. When I load the page it says nan and undefined. Any help is appreciated. Thankyou!
This is my JavaScript code:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
document.write("<br>");
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
document.write("Type of Products:" + ProductType);
document.write("<br>");
document.write("Number of Products:" + ProductQty);
document.write("<br>");
var GrossAmount =(ProductPrice) * (ProductQty);
document.write("Gross Amount is:" + GrossAmount);
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = (GrossAmount) - (GrossAmount) * (DiscountPercent)
var TotalAmount = (GrossAmount) * (DiscountPercent)
document.write("<br>");
document.write("Discount Amount:" + DiscountAmount)
document.write("<br>");
document.write("Discount Percent:" + DiscountPercent)
document.write("<br>");
document.write("Total Amount:" + TotalAmount)
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
}
else {
document.write("<br>");
document.write("Invalid Product Type");
document.write("<br>");
}
if (ProductQty <1|| ProductQty >100) {
document.write("Invalid Quantity")
}
}
function discountAmt() {
if (GrossAmount <200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount<=399.99) {
DiscountPercent = '.05';
} else if (GrossAmount>=400 && GrossAmount<=599.99 ) {
DiscountPercent = '.075';
} else if (GrossAmount >=600)
DiscountPercent = '.1';
}
This is my HTML Code:
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>
Sorry for the confusion. I was mistaken about the unclosed function. Instead, the problem is that GrossAmount was defined in the calculate function instead of in the outer scope. Therefor, it was not reachable in the discountAmt function.
Here is your fixed code, except with the document.writes removed so that it can run in the sandbox:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
var GrossAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
GrossAmount = ProductPrice * ProductQty;
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = GrossAmount - GrossAmount * DiscountPercent;
var TotalAmount = GrossAmount * DiscountPercent;
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
} else {}
if (ProductQty < 1|| ProductQty > 100) {}
console.log('ProductPrice: ', ProductPrice);
}
function discountAmt() {
if (GrossAmount < 200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount <= 399.99) {
DiscountPercent = '.05';
} else if (GrossAmount >= 400 && GrossAmount <= 599.99) {
DiscountPercent = '.075';
} else if (GrossAmount >= 600) {
DiscountPercent = '.1';
}
console.log('DiscountPercent: ', DiscountPercent);
}
calculate();
Obviously you are not closing the elsestatement function ie } is missing. and manage the code like this
change
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>
to
<!DOCTYPE html>
<html>
<title>Product</title>
<script src="Product.js"> </script>
<body>
<h1>Product Calc</h1>
</body>
<script>
$(function(){
calculate();
});
</script>

char counter doesn't work with paste event

I have written a code bellow for counting the character inside text box.
the code is working just fine the only problem with it is when i past a text into the text box i have to press any key so system start to count.
Could you please help me sort this problem
function GetAlhpa(text) {
var gsm = "#£$¥èéùìòÇØøÅåΔ_ΦΓΛΩΠΨΣΘΞ^{}\[~]|€ÆæßÉ!\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
var i = 0;
while (i <= String(text).length) {
if (gsm.indexOf(String(String(text).charAt(i))) == -1 && (String(text).charCodeAt(i) != 32) && (String(text).charCodeAt(i) != 27) && (String(text).charCodeAt(i) != 10) && (String(text).charCodeAt(i) != 13)) {
UniCodestring = " Unicode ";
Countsms = 70;
if ($('#SndSms_Message').val().length > 70)
Countsms = 67;
return;
}
i++;
}
Countsms = 160;
UniCodestring = "";
if ($('#SndSms_Message').val().length > 160)
Countsms = 153;
}
var Countsms = 160;
var UniCodestring = "";
var CounterSmsLen = 0;
var Two = "|^€{}[]~";
function GetCountSms() {
document.getElementById('SndSms_Message').addEventListener('input', function (e) {
var target = e.SndSms_Message,
position = SndSms_Message.selectionStart;
ConvertGreek();
CounterSmsLen = $('#SndSms_Message').val().length;
GetAlhpa($('#SndSms_Message').val());
var i = 0;
while (i < String(Two).length) {
var oldindex = -1;
while (String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) > -1) {
//if ( String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i))) > -1){
CounterSmsLen += 1;
oldindex = String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) + 1;
console.log(i);
}
i++;
}
SndSms_Message.selectionEnd = position; // Set the cursor back to the initial position.
});
if ($('#SndSms_Message').val().length == 0)
CounterSmsLen = 0;
$('#SndSms_Count').html(' ' + CounterSmsLen + ' Characters' + UniCodestring + ' <br /> ' + Math.ceil(CounterSmsLen / Countsms) + ' Sms');
countsmsnumber=Math.ceil(CounterSmsLen / Countsms);
}
var greekchar = "ΑΒΕΖΗΙΚΜΝΟΡΤΥΧ";
var englishchar = "ABEZHIKMNOPTYX";
function ConvertGreek() {
var str = $('#SndSms_Message').val();
var i = 0;
while (i < String(greekchar).length) {
str = str.replace(new RegExp(String(greekchar).charAt(i), 'g'), String(englishchar).charAt(i));
i++;
}
$('#SndSms_Message').val(str);
P.S.
If i paste the number into the text box it will count it correct but if i paste character it wont count them..
You need keyup change event in order to handle paste event.
document.getElementById('SndSms_Message').addEventListener("keyup", function() {
//your code here
});
example

Why am I not being redirected to a new page?

So this is a flappy bird kinda game. I have been trying to move the user to a new url once the user hits the score 5. The game works fine but I am not being redirected to the page and the game keeps running.
Script :
$(function () {
//saving dom objects to variables
var container = $('#container');
var bird = $('#bird');
var pole = $('.pole');
var pole_1 = $('#pole_1');
var pole_2 = $('#pole_2');
var score = $('#score');
var speed_span = $('#speed');
var restart_btn = $('#restart_btn');
//saving some initial setup
var container_width = parseInt(container.width());
var container_height = parseInt(container.height());
var pole_initial_position = parseInt(pole.css('right'));
var pole_initial_height = parseInt(pole.css('height'));
var bird_left = parseInt(bird.css('left'));
var bird_height = parseInt(bird.height());
var speed = 10;
//some other declarations
var go_up = false;
var score_updated = false;
var game_over = false;
var the_game = setInterval(function () {
if (collision(bird, pole_1) || collision(bird, pole_2) || parseInt(bird.css('top')) <= 0 || parseInt(bird.css('top')) > container_height - bird_height)
{
stop_the_game();
} else {
var pole_current_position = parseInt(pole.css('right'));
//update the score when the poles have passed the bird successfully
if (pole_current_position > container_width - bird_left) {
if (score_updated === false) {
score.text(parseInt(score.text()) + 1);
score_updated = true;
if(score.text(parseInt(score.text()))==5){
window.location.href = "http://fb.com";
}
}
}
//check whether the poles went out of the container
if (pole_current_position > container_width) {
var new_height = parseInt(Math.random() * 100);
//change the pole's height
pole_1.css('height', pole_initial_height + new_height);
pole_2.css('height', pole_initial_height - new_height);
//increase speed
speed = speed + 1;
speed_span.text(speed);
score_updated = false;
pole_current_position = pole_initial_position;
if(score.text(parseInt(score.text()))==5){
window.location.href = "http://fb.com";
}
}
//move the poles
pole.css('right', pole_current_position + speed);
if (go_up === false){
go_down();
}
}
},
40);
$(document).on('keydown', function (e) {
var key = e.keyCode;
if (key === 32 && go_up === false && game_over === false) {
go_up = setInterval(up, 50);
}
});
$(document).on('keyup', function (e) {
var key = e.keyCode;
if (key === 32) {
clearInterval(go_up);
go_up = false;
}
});
function go_down() {
bird.css('top', parseInt(bird.css('top')) + 5);
}
function up() {
bird.css('top', parseInt(bird.css('top')) - 10);
}
function stop_the_game() {
clearInterval(the_game);
game_over = true;
restart_btn.slideDown();
}
restart_btn.click(function () {
location.reload();
});
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var y1 = $div1.offset().top;
var h1 = $div1.outerHeight(true);
var w1 = $div1.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var y2 = $div2.offset().top;
var h2 = $div2.outerHeight(true);
var w2 = $div2.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
return true;
}
});
HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>FlattyBird</title>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<!-- Testing the git command line tool-->
<div id="container">
<div id="bird"></div>
<div id="pole_1" class="pole"></div>
<div id="pole_2" class="pole"></div>
</div>
<div id="score_div">
<p><b>Score: </b><span id="score">0</span></p>
<p><b>Speed: </b><span id="speed">10</span></p>
</div>
<button id="restart_btn">Restart</button>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Try
if(score.text(parseInt(score.text()))=="5"){
window.location.href = "http://fb.com";
}
Or
if(parseInt(score.text())==5){
window.location.href = "http://fb.com";
}
Your if is probably not evaluating to true.
if(score.text(parseInt(score.text()))==5){
window.location.href = "http://fb.com";
}

Categories

Resources