vertical bar chart with with user input and validation - javascript

i need a make a code where the user can add the max points, achieved points and his name. this is my code..most things are already working, i just need a function to change the max points, right now its a static number.
<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 = 100;
var barWidth = 75;
window.onload = function() { document.getElementsByTagName('input')[0].value = maxPoints; } function setMaxPoints() { maxPoints = document.getElementsByTagName('input')[0].value; }
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();
};
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>
<label><input size="5" onkeyup="setMaxPoints()" /> Set Max Points</label><br /><br />
<button onclick="gatherData()">Add Participant</button>
<h4>Chart</h4>
<div id="chart"></div>
</body>

Kentas, here is my entire version of your code with the addition of an input box to get maxPoints:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>examAnalysis</title>
<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 = 20;
window.onload = function()
{
document.getElementsByTagName('input')[0].value = maxPoints;
}
function setMaxPoints()
{
maxPoints = document.getElementsByTagName('input')[0].value;
}
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();
};
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.marginBottom = '5px';
bar.style.backgroundColor = getRandomColor();
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>
<label><input size="5" onkeyup="setMaxPoints()" /> Set Max Points</label><br /><br />
<button onclick="gatherData()">Add Participant</button>
<h4>Chart</h4>
<div id="chart"></div>
</body>

Related

My Code for web resources javascript is running on chrome but not in IE 11 of dynamics crm

My java-script Code for on-load event is running successfully in chrome and not working in IE 11. Don't know why its happening .Please help me, i searched a lot and not found the correct solutions.i am working the java-script for dynamics crm 2011 but not able to get the job done.Any changes is not showing in IE 11 but showing in chrome.I am adding my code below.
function calculateManHour() {
debugger;
var advantageManHourCost = 0;
var engageManHourCost = 0;
var advantageManDayCost = 0;//new
var engageManDayCost = 0;//new
var advantageManHour = 0;
var engageManHour = 0;
var advantageManDay = 0;//new
var engageManDay = 0;//new
var currentQuoteProductId = Xrm.Page.data.entity.getId().toString().split("{")[1].split("}")[0];
var costPricePerUnit = parseFloat(Xrm.Page.getAttribute("costprice").getValue());
var serviceProvider = Xrm.Page.getAttribute("serviceprovider").getValue()[0].name;
var quoteProductType = Xrm.Page.getAttribute("quoteproducttype").getValue();
var quoteProductElem = Xrm.Page.getAttribute("quoteproducttype");
var config = getRecord("manhourcostconfigSet", "2A7F8D4D-10C4-E911-943A-00155D1E13EA");
var currentQuoteProduct = getRecord("QuoteDetailSet", currentQuoteProductId);
advantageManHourCost = parseFloat(config.ManHourCost.Value);
engageManHourCost = parseFloat(config.EngageManhourcost.Value);
advantageManDayCost = parseFloat(config.AdvantageMandaycost.Value);//new
engageManDayCost = parseFloat(config.EngageMandaycost.Value);//new
if (quoteProductType == false) {
Xrm.Page.getAttribute("valueoffering").setValue(true);
if (serviceProvider == "Services_ADVANTAGE") {
advantageManHour = costPricePerUnit / advantageManHourCost;
advantageManDay = costPricePerUnit / advantageManDayCost;
engageManHour = null;
engageManDay = null;
Xrm.Page.getControl("engagebudgetedmanhours").setVisible(false);
Xrm.Page.getControl("engagemandaycost").setVisible(false);
setTooltip("advantagemandaycost", advantageManDayCost, "advantagebudgetedmanhours", advantageManHourCost);
}
if (serviceProvider == "Services_ENGAGE") {
engageManHour = costPricePerUnit / engageManHourCost;
engageManDay = costPricePerUnit / engageManDayCost;
advantageManHour = null;
advantageManDay = null;
Xrm.Page.getControl("advantagebudgetedmanhours").setVisible(false);
Xrm.Page.getControl("advantagemandaycost").setVisible(false);
setTooltip("engagemandaycost", engageManDayCost, "engagebudgetedmanhours", engageManHourCost);
}
var data = {
"engagebudgetedmanhours": engageManHour,
"advantagebudgetedmanhours": advantageManHour,
"engagemandaycost": engageManDay,
"advantagemandaycost": advantageManDay
}
Xrm.Page.getAttribute("advantagebudgetedmanhours").setValue(advantageManHour);
Xrm.Page.getAttribute("engagebudgetedmanhours").setValue(engageManHour);
Xrm.Page.getAttribute("advantagemandaycost").setValue(advantageManDay);//new
Xrm.Page.getAttribute("engagemandaycost").setValue(engageManDay);//new
Xrm.Page.getAttribute("engagebudgetedmanhours").setSubmitMode("always");
Xrm.Page.getAttribute("advantagebudgetedmanhours").setSubmitMode("always")
Xrm.Page.getAttribute("engagemandaycost").setSubmitMode("always");//new
Xrm.Page.getAttribute("advantagemandaycost").setSubmitMode("always")//new
Xrm.Page.data.entity.save();
}
}
function setTooltip(attribute1, tip1, attribute2, tip2) {
debugger;
try {
if (!attribute1 || !tip1 && !attribute2 || !tip2) {
return;
}
var control1 = Xrm.Page.getControl(attribute1);
var control2 = Xrm.Page.getControl(attribute2);
if (!control1 || !control2) {
return;
}
var element1 = document.getElementById(attribute1 + "_d");
var element2 = document.getElementById(attribute2 + "_d");
if (!element1 || !element2) {
return;
}
var tooltipSpan1 = document.createElement("span");
tooltipSpan1.id = attribute1 + "_tooltip";
tooltipSpan1.textContent = "Man Day Cost is = " + tip1;
tooltipSpan1.setAttribute(
"style",
"display: none; width: 120px; background-color: #fdfafa; color: ; rgb(23, 22, 22): center; padding: 5px 5px; border-radius: 3px;" +
"border: 1px solid black;z-index: 1;"
);
var tooltipSpan2 = document.createElement("span");
tooltipSpan2.id = attribute1 + "_tooltip";
tooltipSpan2.textContent = "Man Hour Cost is = " + tip2;
tooltipSpan2.setAttribute(
"style",
"display: none; width: 120px; background-color: #fdfafa; color: ; rgb(23, 22, 22): center; padding: 5px 5px; border-radius: 3px;" +
"border: 1px solid black;z-index: 1;"
);
element1.appendChild(tooltipSpan1);
element2.appendChild(tooltipSpan2);
document.getElementById(attribute1 + "_c").setAttribute("title", "Man Day Cost is = " + tip1);
document.getElementById(attribute2 + "_c").setAttribute("title", "Man Hour Cost is = " + tip2);
element1.addEventListener("mouseover", (e) => {
tooltipSpan1.style.display = "inline";
tooltipSpan1.style.top = (e.clientX + 20) + 'px';
tooltipSpan1.style.left = (e.clientY + 20) + 'px';
});
element1.addEventListener("mouseout", (e) => {
tooltipSpan1.style.display = "none";
});
element2.addEventListener("mouseover", (e) => {
tooltipSpan2.style.display = "inline";
tooltipSpan2.style.top = (e.clientX + 20) + 'px';
tooltipSpan2.style.left = (e.clientY + 20) + 'px';
});
element2.addEventListener("mouseout", (e) => {
tooltipSpan2.style.display = "none";
});
} catch (e) {
console.log(e);
}
}
You're using arrow => functions. IE11 doesn't support them. Arrow function come under ES6 which is not yet supported by IE11.
There are lot of online tools which will help you convert ES6 to Es5
Convert below function
element1.addEventListener("mouseover", (e) => {
tooltipSpan1.style.display = "inline";
tooltipSpan1.style.top = (e.clientX + 20) + 'px';
tooltipSpan1.style.left = (e.clientY + 20) + 'px';
});
to something like below
element1.addEventListener("mouseover", function(e) {
tooltipSpan1.style.display = "inline";
tooltipSpan1.style.top = (e.clientX + 20) + 'px';
tooltipSpan1.style.left = (e.clientY + 20) + 'px';
});

Tracking time and display it at next game

I have an assignment and I am a bit stuck. The assignment states:
Modify the game so that the time is tracked and a best time (or time to beat) is stored and displayed at the end of the game and at the beginning of the next game that is played. This functionality assumes the browser is not closed and that each successive game is begun through the "Play Again?" link. The display of the time to beat is shown below.
I have all files necessary, but I am stuck in this part. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var matchesFoundText;
var tileHeight = 30;
var tileWidth = 45;
var border = 1;
var globalPadding = 10;
var margin = 10;
var padding = 5;
var textTiles;
var flashcards = [
["a", "\u3042"],
["i", "\u3044"],
["u", "\u3046"],
["e", "\u3048"],
["o", "\u304A"],
["ka", "\u304B"],
["ki", "\u304D"],
["ku", "\u304F"],
["ke", "\u3051"],
["ko", "\u3053"],
["sa", "\u3055"],
["shi", "\u3057"],
["su", "\u3059"],
["se", "\u305B"],
["so", "\u305D"],
["ta", "\u305F"],
["chi", "\u3061"],
["tsu", "\u3064"],
["te", "\u3066"],
["to", "\u3068"],
["na", "\u306A"],
["ni", "\u306B"],
["nu", "\u306C"],
["ne", "\u306D"],
["no", "\u306E"],
["ha", "\u306F"],
["hi", "\u3072"],
["fu", "\u3075"],
["he", "\u3078"],
["ho", "\u307B"],
["ma", "\u307E"],
["mi", "\u307F"],
["mu", "\u3080"],
["me", "\u3081"],
["mo", "\u3082"],
["ya", "\u3084"],
["yu", "\u3086"],
["yo", "\u3088"],
["ra", "\u3089"],
["ri", "\u308A"],
["ru", "\u308B"],
["re", "\u308C"],
["ro", "\u308D"],
["wa", "\u308F"],
["wo", "\u3092"],
["n", "\u3093"]
];
function init() {
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
totalMatchesPossible = flashcards.length;
var numberOfTiles = totalMatchesPossible * 2;
matchesFound = 0;
var columns = 12;
timeAllowable = 500;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top";
txt.x = 700;
txt.y = 0;
stage.addChild(txt);
textTiles = [];
matchesFoundText = new Text(matchesFound + "/" + totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top";
matchesFoundText.x = 700;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
setPlacementArray(numberOfTiles);
for (var i = 0; i < numberOfTiles; i++) {
var placement = getRandomPlacement(placementArray);
var pairIndex = Math.floor(i / 2);
text = flashcards[pairIndex][i % 2];
var textTile = drawTextTile(text, pairIndex);
textTile.x = (tileWidth + margin) * (placement % columns) + globalPadding;
textTile.y = (tileHeight + margin) * Math.floor(placement / columns) + globalPadding;
stage.addChild(textTile);
background = new Shape();
background.x = textTile.x - padding;
background.y = textTile.y - padding;
background.graphics.setStrokeStyle(border).beginStroke("#000").beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
textTiles.push(background);
stage.addChildAt(background);
background.text = textTile;
background.onPress = handleOnPress;
stage.update();
};
}
function drawTextTile(text, pairIndex) {
textTile = new Text(text, "20px Monospace", "#000");
textTile.pairIndex = pairIndex;
textTile.textBaseline = "top";
return textTile;
}
function randomColor() {
var color = Math.floor(Math.random() * 255);
var color2 = Math.floor(Math.random() * 255);
var color3 = Math.floor(Math.random() * 255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles) {
for (var i = 0; i < numberOfTiles; i++) {
placementArray.push(i);
}
}
function getRandomPlacement(placementArray) {
randomNumber = Math.floor(Math.random() * placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event) {
var tile = event.target;
if (!!tileClicked === false || tileClicked === tile) {
tileClicked = tile;
} else {
tileClicked.graphics.beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
tile.graphics.beginFill('#aae').drawRect(0, 0, tileWidth, tileHeight);
if (tileClicked.text.pairIndex === tile.text.pairIndex && tileClicked.id != tile.id) {
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = matchesFound + "/" + totalMatchesPossible;
if (matchesFound === totalMatchesPossible) {
gameOver(true);
}
}
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
} else {
txt.text = secondsLeft + "... Game Over";
}
}
function replay() {
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
I give you 1 option for this, though you can do it also in other ways,
we declare global variables which are
var prev_time;
var best_time;
add that to your global variable declarations, then give it a value when you compute the time i guess we had that here:
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
//compute here the total time player had and give it to prev_time
//var totalTimePlayerplayed = some computation here which should be allowed time per player - secondsLeft
prev_time = totalTimePlayerplayed;
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play A
gain?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
if(best_time !== NULL){
best_time = prev_time;
//WE assume that the last player is the best scorer
}
} else {
//if there is already existing top scorer
if(best_time < prev_time){
best_time = prev_time
}
txt.text = secondsLeft + "... Game Over";
}
}
then give that time of the first player to the prev_time. Upon Game over or Game ended we validate here if the best_time has a value if not, then we give it a value of the value of prev_time, else we validate if the score is higher that the previous best_time and here's a tip, now when the player would trigger the "Play again" which I can't seem find right now, you get the variable best_time's value and display it as the score to beat. Hope you get the concept and somehow it helped you accomplished what you're intended to do, but like i said before you also have some other options to do this.

Error code JS with my function Game Over

I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.
var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');
for( var i = 0; i <= 8; i++){
$contener.innerHTML += "<div class='case case" + i + "'></div>";
}
if(localStorage.getItem('score')){
$bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
localStorage.setItem('score', 0);
$bestscore.textContent = 'Score : 0';
}
function decompte(){
if(compte <= 1) {
pluriel = "";
} else {
pluriel = "s";
}
$compt.innerHTML = compte + " seconde" + pluriel;
if(!compte || compte < 0) {
reset();
if(pointCounter > localStorage.getItem('score')){
localStorage.setItem('score', pointCounter);
$bestscore.textContent = 'Score : ' + pointCounter;
}
}
//decrease 1 point
compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);
//RANDOM POSITION
function randomPosition() {
var $cases = document.querySelectorAll('.case');
// cannot click 2 times
for (var i =0; i< $cases.length; i++){
$cases[i].removeEventListener('click', losePoints);
$cases[i].removeEventListener('click', earnPoints);
$cases[i].innerHTML = '';
}
var x = Math.floor(Math.random() * 9);
var min = 1;
var max = 7;
var nbrRandom = min + Math.floor(Math.random() * max);
if (nbrRandom === 2) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/darkTaupiqueur.png" alt="darktopiqueur"/></div>';
$cases[x].addEventListener('click', losePoints);
} else if(nbrRandom ===6) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/Marteau_TFH.png" alt="marteau"/></div>';
$cases[x].addEventListener('click', gameOver);
}
else
{
$cases[x].innerHTML = '<div id="taupe"><img src="images/Taupiqueur.png" alt="t opiqueur"/></div>';
$cases[x].addEventListener('click', earnPoints);
}
}
function losePoints(event){
/* JouerSon(); */
pointCounter -=10;
if(pointCounter <0){
pointCounter =0
}
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', losePoints);
}
function earnPoints(event){
/* JouerSon(); */
pointCounter ++;
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', earnPoints);
}
/*function JouerSon() {
var sound = document.getElementById("beep");
sound.play();
} */
// RESET BUTTON
function reset(){
$button.classList.remove("reset");
$button.addEventListener('click', resetGame);
clearInterval(timer);
clearInterval(taupe);
}
function resetGame(){
pointCounter = 0;
compte = temps;
$score.textContent = pointCounter;
timer = setInterval(decompte,1000);
taupe = setInterval(randomPosition,1000);
$button.removeEventListener('click', resetGame);
$button.classList.add('reset');
}
function gameOver(event){
event.currentTarget.removeEventListener('click', gameOver);
alert("GAME OVER");
reset();
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<meta charset="utf-8"/>
</head>
<body>
<span id="compt"></span>
<span id="score">Score : </span> <span id="bestscore"></span>
<div class="contener"></div>
<button class="resetBouton reset"> reset </button>
<button class="resetBouton jouer"> Jouer </button>
<audio id="beep" src="test1.wav">
<script type='text/javascript' src="script/main.js"></script>
</body>
</html>
From a quick examination of your game, it looks like you are calling randomPosition every second, selecting a random element and then attaching one of three event handlers to it.
It looks like you are removing your losePoints and earnPoints handlers on each call to randomPosition, but never removing gameOver.

Chrome Extension JavaScript Error

I am trying to deploy a html+jss+css project of a pattern password as a chrome extension. On my local machine the code works as expected. However when I test it as a chrome extension, the box in which the pattern is to be entered is not displayed.
Code Below :
index.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=320; user-scalable=no; initial-scale=1.0; maximum-scale=1.0" />
<title>Pattern Lock Welcome Page</title>
<link rel="stylesheet" type="text/css" href="assets/css/main.css"/>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div id="jquery-script-menu">
<div class="jquery-script-clear"></div>
</div>
</div>
<h1 style="margin:150px auto 20px auto; text-align:center; color:#fff">Pattern Lock</h1>
<div class="maincontainer">
<h2 id="heading" class="heading">Please set your password</h2>
<div id="patterncontainer" class="patterncontainer">
</div>
</div>
</body>
<script src="js/script.js"></script>
</html>
welcome.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=320; user-scalable=no; initial-scale=1.0; maximum-scale=1.0" />
<title>Pattern Lock</title>
<link rel="stylesheet" type="text/css" href="assets/css/main.css"/>
</head>
<body>
<div class="maincontainer">
<h2 id="heading" class="heading">Homescreen</h2>
<button id="lockScreen" class="button-lockscreen" onclick="window.location= './index.html';">Lock Screen</a><br /><br />
<button id="resetPassword" class="button-reset" onclick="resetPassword()">Reset Password</a>
</div>
</body>
<script type="text/javascript" src="js/homepage.js"></script>
</html>
homepage.js
function resetPassword() {
console.log("sdfsdf");
if (localStorage.getItem("password")) {
alert("Pattern : "+localStorage.getItem("password"));
localStorage.removeItem("password");
successmessage("resetSuccess");
} else {
emptyPassword();
}
};
(function checkPassword(){
if (!localStorage.getItem("password")) {
emptyPassword();
}
}());
function successmessage(successcode) {
if (successcode == "resetSuccess") {
alert("Pattern Reset Success!");
}
location.reload();
};
function emptyPassword() {
document.getElementById("resetPassword").style.display = "none";
document.getElementById("lockScreen").innerHTML = "Set Password";
};
script.js
$(document).ready(function(){
var errorraised = false;
var passwordset = false;
var getClickStarted = false;
var autosubmit = true;
var password;
var centerX1;
var centerY1;
var curX = 0;
var curY = 0;
var getClickStarted = false;
var htmlLine;
var startpointnumber=0;
var endpointnumber=0;
(function checkIfPasswordIsSet() {
if (localStorage.getItem("password")) {
document.getElementById("heading").innerHTML = "Enter pattern to unlock screen";
passwordset = true;
}
else {
document.getElementById("heading").innerHTML = "Please set your pattern";
}
}());
(function generatebuttons(){
var patterncontainer = document.getElementById("patterncontainer");
for (var i = 1; i <=9; i++) {
var button = document.createElement("div");
button.className = "button";
button.id = "button" + i;
patterncontainer.appendChild(button);
startposition = document.getElementById("button" + i);
}
}());
(function main(){
if(!window.navigator.msPointerEnabled) {
$(".button").on("mousedown", function (event){
if(!getClickStarted){
getClickStarted = true;
var offset1 = $("#" + event.target.id).position();
centerX1 = offset1.left + $("#" + event.target.id).innerWidth()/2 + 20.5; //22.5 is the margin of the button class
centerY1 = offset1.top + $("#" + event.target.id).innerHeight()/2 + 20.5;
//console.log("centerX1 " + centerX1);
//console.log("centerY1 " + centerY1);
if (event && event.preventDefault){
event.preventDefault();
}
$("#" + event.target.id).removeClass("button").addClass("activebutton");
password = event.target.id.split("button").join("");
startpointnumber = event.target.id.split("button").join("");
//console.log("startpointnumber " + startpointnumber);
addline(startpointnumber, centerX1, centerY1); //initiating a moving line
}
});
$(document).bind("mousemove", function(event) {
if (getClickStarted){ //to avoid mousemove triggering before click
if (event && event.preventDefault){
event.preventDefault();
}
curX = event.clientX - $("#patterncontainer").offset().left;
curY = event.clientY - $("#patterncontainer").offset().top;
var width = Math.sqrt(Math.pow(curX - centerX1, 2) + Math.pow(curY - centerY1, 2)); //varying width and slope
var slope = Math.atan2(curY - centerY1, curX - centerX1)*180/3.14;
//setting varying width and slope to line
$("#line" + startpointnumber).css({"width": + width +"px", "height": "4px", "transform": "rotate(" + slope + "deg)", "-webkit-transform": "rotate(" + slope + "deg)", "-moz-transform": "rotate(" + slope + "deg)"});
//if button is found on the path
$(".button").bind("mouseover", function(e) {
endpointnumber = e.target.id.split("button").join("");
if (startpointnumber != endpointnumber) {
if (e && e.preventDefault){
e.preventDefault();
}
if (e.target.className == "button") {
$("#" + e.target.id).removeClass("button").addClass("activebutton");
} else {
$("#" + e.target.id).removeClass("activebutton").addClass("duplicatebutton");
}
password += e.target.id.split("button").join("");
// endpointnumber = e.target.id.split("button").join("");
$("#line" + startpointnumber).attr("id", "line" + startpointnumber + endpointnumber);
var offset2 = $("#" + e.target.id).position();
var centerX2 = offset2.left + $("#" + e.target.id).innerWidth()/2 + 20.5; //20.5 is the margin of activebutton class
var centerY2 = offset2.top + $("#" + e.target.id).innerHeight()/2 + 20.5;
var linewidth = Math.sqrt(Math.pow(centerX2 - centerX1, 2) + Math.pow(centerY2 - centerY1, 2));
var lineslope = Math.atan2(centerY2 - centerY1, centerX2 - centerX1)*180/3.14;
$("#line" + startpointnumber + endpointnumber).css({"width": + linewidth +"px", "transform": "rotate(" + lineslope + "deg)", "-webkit-transform": "rotate(" + lineslope + "deg)", "-moz-transform": "rotate(" + lineslope + "deg)"});
startpointnumber = endpointnumber;
centerX1 = centerX2;
centerY1 = centerY2;
addline(startpointnumber, centerX1, centerY1);
}
});
}
$("#patterncontainer").on("mouseup", function (event){
if(getClickStarted) {
if (event && event.preventDefault){
event.preventDefault();
}
$("#line" + startpointnumber).remove();
if (autosubmit) {
formsubmit();
}
}
getClickStarted = false;
});
});
} else {
alert ("INTERNET EXPLORER NOT SUPPORTED!!");
}
}());
function addline(startpointnumber, centerX1, centerY1){
var htmlLine = "<div id='line" + startpointnumber + "' class='line' style='position: absolute; top: " + centerY1 + "px; \
left: " + centerX1 + "px; -webkit-transform-origin: 2px 2px; -moz-transform-origin: 2.5% 50%; background-color: #FFF;'></div>"
$("#patterncontainer").append(htmlLine);
}
function formsubmit(){
var digits = getlength(password);
if(digits<5) {
raiseerror("lengthTooSmall");
}
checkduplicatedigits(password);
if (errorraised == false && passwordset == false) {
localStorage.setItem("password", password);
successmessage("patternStored");
}
else if ( errorraised == false && passwordset == true) {
if (localStorage.getItem("password") == password) {
successmessage("screenUnlocked");
window.location = "./welcome.html";
return false;
}
else {
raiseerror("IncorrectPattern");
}
}
};
function getlength(number) {
return number.toString().length;
};
function checkduplicatedigits(number) {
var digits = getlength(number);
numberstring = number.toString();
var numberarray = numberstring.split("");
var i; var j;
for (i = 0; i < digits-1; i++) {
for (j = i+1; j < digits; j++) {
if(numberarray[i] == numberarray[j]) {
raiseerror("repeatedEntry");
}
}
}
};
function successmessage(successcode) {
if(successcode == "screenUnlocked") {
alert("You have unlocked the screen!");
}
if (successcode == "patternStored") {
alert("Your pattern is stored. Thanks.");
passwordset = true;
}
if (successcode == "Success") {
alert("Pattern Reset Success!");
}
location.reload();
};
function raiseerror(errorcode) {
if(!errorraised){
errorraised = true;
if (errorcode == "lengthTooSmall") {
alert("The pattern is too short. Please try again.");
}
if (errorcode == "repeatedEntry") {
alert("You cannot use the same number twice. Please try again.");
}
if (errorcode == "IncorrectPattern") {
alert("The entered pattern in incorrect. Please try again.");
}
if (errorcode == "emptyPassword") {
alert("You did not set the password to reset it.");
}
location.reload();
}
};
});
and lastly this is my manifest.json :
{
"manifest_version": 2,
"name": "GRAphical Pass",
"description": "THIS IS SPARTA!!!!!!",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "index.html"
},
"permissions": [
"activeTab"
]
}
Any help would be much appreciated. Thanks :)
Expected(this is what I get on my machine)
But deploying it as an extension :
this is what I get
I suggest removing : $(document).ready(function(){
from your scripts and adding
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["homepage.js","script.js"]
}
],
to your manifest along with the following CSP :
"content_security_policy": "script-src 'self' https://code.jquery.com; object-src 'self'"

How to make this ajax checker for multiple fields in the form?

I have the code below where it validates the form. How do i make it so i can reuse the code for other fields besides username?
How do i make it so i can have multiple other fields and use the same jquery code for validation?
<form name="form" id="form" class="form" action="success.html"
onsubmit="return validate(this)" method="post">
<label for="username">User Name:</label>
<input type="text" name="username" id="username" />
<label for="fullname">Full Name:</label>
<input type="text" name="fullname" id="fullname" />
<input type="submit" value="Submit" class="submit" />
</form>
And here is the jquery:
// form validation function //
function validate(form) {
var username = form.username.value;
var usernameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
if(username == "") {
inlineMsg('username','You must enter your username.',2);
return false;
}
if(!username.match(usernameRegex)) {
inlineMsg('username','You have entered an invalid username.',2);
return false;
}
if(username.length>20){
inlineMsg('username','Username is too long (max 20 char)', 2);
return false;
}
return true;
}
// START OF MESSAGE SCRIPT //
var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;
// build out the divs, set attributes and call the fade function
function inlineMsg(target,string,autohide) {
var msg;
var msgcontent;
if(!document.getElementById('msg')) {
msg = document.createElement('div');
msg.id = 'msg';
msgcontent = document.createElement('div');
msgcontent.id = 'msgcontent';
document.body.appendChild(msg);
msg.appendChild(msgcontent);
msg.style.filter = 'alpha(opacity=0)';
msg.style.opacity = 0;
msg.alpha = 0;
} else {
msg = document.getElementById('msg');
msgcontent = document.getElementById('msgcontent');
}
msgcontent.innerHTML = string;
msg.style.display = 'block';
var msgheight = msg.offsetHeight;
var targetdiv = document.getElementById(target);
targetdiv.focus();
var targetheight = targetdiv.offsetHeight;
var targetwidth = targetdiv.offsetWidth;
var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
msg.style.top = topposition + 'px';
msg.style.left = leftposition + 'px';
clearInterval(msg.timer);
msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
if(!autohide) {
autohide = MSGHIDE;
}
window.setTimeout("hideMsg()", (autohide * 1000));
}
// hide the form alert //
function hideMsg(msg) {
var msg = document.getElementById('msg');
if(!msg.timer) {
msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
}
}
// face the message box //
function fadeMsg(flag) {
if(flag == null) {
flag = 1;
}
var msg = document.getElementById('msg');
var value;
if(flag == 1) {
value = msg.alpha + MSGSPEED;
} else {
value = msg.alpha - MSGSPEED;
}
msg.alpha = value;
msg.style.opacity = (value / 100);
msg.style.filter = 'alpha(opacity=' + value + ')';
if(value >= 99) {
clearInterval(msg.timer);
msg.timer = null;
} else if(value <= 1) {
msg.style.display = "none";
clearInterval(msg.timer);
}
}
// calculate the position of the element in relation to the left
of the browser //
function leftPosition(target) {
var left = 0;
if(target.offsetParent) {
while(1) {
left += target.offsetLeft;
if(!target.offsetParent) {
break;
}
target = target.offsetParent;
}
} else if(target.x) {
left += target.x;
}
return left;
}
// calculate the position of the element in relation to the
top of the browser window //
function topPosition(target) {
var top = 0;
if(target.offsetParent) {
while(1) {
top += target.offsetTop;
if(!target.offsetParent) {
break;
}
target = target.offsetParent;
}
} else if(target.y) {
top += target.y;
}
return top;
}
// preload the arrow //
if(document.images) {
arrow = new Image(7,80);
arrow.src = "images/msg_arrow.gif";
}
Here is a plugin I used in the past:
https://github.com/posabsolute/jQuery-Validation-Engine
Take a look in there and it might be good for you. I personally modified it to fit my needs but that's a bit extreme.
You should never have to re-invent the wheel :)

Categories