No output in console.log. Beginner Question - javascript

I'm reading Head 1st JavaScript book and try to learn the language as much as i can. Wanted to to all the problems from the book. After i did so for one of the problems, and wrote the code as i thought, and checked the solution, i changed it to reflect the solution in the book even thou it worked for me. The thing is, when i want to "print" in the console now, nothing shows up and idk why... i don't see nor have a problem...
Any idea why the console.log will not output anything? Thanks!
<!DOCTYPE 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.0">
<title>Document</title>
<script>
function Coffee(roast, ounces) {
this.roast = roast;
this.ounces = ounces;
this.getSize = function() {
if (this.ounces === 8) {
return "small";
} else if (this.ounces === 12) {
return "medium";
} else (this.ounces === 16); {
return "large";
}
};
this.toString = function() {
return "You have ordered a " + this.getSize() + " " + this.roast + " coffee.";
};
}
var csmall = new Coffee ("House Blend", "8");
var cmedium = new Coffee ("House Blend", "12");
var clarge = new Coffee ("Dark Roast", "16");
var coffees = [csmall, cmedium, clarge];
for (var i = 0; i < coffees.length; i++) {
coffees[i].toString();
}
</script>
</head>
<body>
</body>
</html>
This is the way i wrote the code and worked.
<!DOCTYPE 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.0">
<title>Document</title>
<script>
function Coffee(roast, size, ounces) {
this.roast = roast;
this.size = size;
this.ounces = ounces;
this.getSize = function() {
if (this.ounces === 8) {
console.log("You have ordered a " + this.size + " " + this.roast + " coffee.");
} else if (this.ounces === 12) {
console.log("You have ordered a " + this.size + " " + this.roast + " coffee.");
} else (this.ounces === 16); {
console.log("You have ordered a " + this.size + " " + this.roast + " coffee.");
}
};
}
var csmall = new Coffee ("House Blend", "small", "8");
var cmedium = new Coffee ("House Blend", "medium", "12");
var clarge = new Coffee ("Dark Roast", "large", "16");
var coffees = [csmall, cmedium, clarge];
for (var i = 0; i < coffees.length; i++) {
coffees[i].getSize();
}
</script>
</head>
<body>
</body>
</html>

In above code console log has not been used so this is why you haven't seen any thing in the console
for (var i = 0; i < coffees.length; i++) {
coffees[i].toString();
console.log(String(coffees[i])); // <-- add here
}
Still it would give incorrect result becuase it used === in the function which means the type of the value supplied will also match with type in the function
It used integers in function but supplied value in string see the code below
if (this.ounces === 8) { // used === to match type as well here it is integer
return "small";
} else if (this.ounces === 12) {
return "medium";
} else (this.ounces === 16); {
return "large";
}
};
this.toString = function() {
return "You have ordered a " + this.getSize() + " " + this.roast + " coffee.";
};
}
var csmall = new Coffee ("House Blend", "8"); // passing it as string "8" it should be just 8
var cmedium = new Coffee ("House Blend", "12");
var clarge = new Coffee ("Dark Roast", "16");
Correct Code should be like this
<script>
function Coffee(roast, ounces) {
this.roast = roast;
this.ounces = ounces;
this.getSize = function() {
if (this.ounces === 8) {
return "small";
} else if (this.ounces === 12) {
return "medium";
} else (this.ounces === 16); {
return "large";
}
};
this.toString = function() {
return "You have ordered a " + this.getSize() + " " + this.roast + " coffee.";
};
}
var csmall = new Coffee ("House Blend", 8);
var cmedium = new Coffee ("House Blend", 12);
var clarge = new Coffee ("Dark Roast", 16);
var coffees = [csmall, cmedium, clarge];
for (var i = 0; i < coffees.length; i++) {
coffees[i].toString();
console.log(String(coffees[i]));
}
</script>
But in the secon code which is done by you...
I beleive the real problem was to use logic and convert ounces into size by getsize function where as you directly used sizes in your solution

Related

My Js file is not linking to my html. What am i doing wrong?

This is my Htnl section, I have put it as shown here, in the head section as well as at the bottom. I have tried it in code pen and have no issues so it has to be how I am linking it to my page?
Ive been stuck on this for awhile. Ive checked my JS code with no errors. I have read everything I can and I have not been able to fix this. should be as simple as attatching to the header but this has not been the case
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="TechPort.css">
<title>Document</title>
<script type="text/javascript" src="TechPort.js"></script>
</head>
<body>
<section class="headline">
<div class="container2">
<div class="text"></div>
</div>
</section>
class TextScramble {
constructor(el) {
this.el = el
this.chars = '!<>-_\\/[]{}—=+*^?#________'
this.update = this.update.bind(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise((resolve) => this.resolve = resolve)
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ''
const to = newText[i] || ''
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({ from, to, start, end })
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update() {
let output = ''
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let { from, to, start, end, char } = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="dud">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
} else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
}
const phrases = [
'Hello!',
'ImHeather',
'IT Support & System Admin',
'Customer Service Expert',
'Tech Junkie',
const el = document.querySelector('.text')
const fx = new TextScramble(el)
let counter = 0
const next = () => {
fx.setText(phrases[counter]).then(() => {
setTimeout(next, 1000)
})
counter = (counter + 1) % phrases.length
}
next()
Do it like this :
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="TechPort.css">
<title>Document</title>
<script type="text/javascript" src="TechPort.js"></script>
</head>
<body>
<section class="headline">
<div class="container2">
<div class="text"></div>
</div>
</section>
<script>
class TextScramble {
constructor(el) {
this.el = el
this.chars = '!<>-_\\/[]{}—=+*^?#________'
this.update = this.update.bind(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise((resolve) => this.resolve = resolve)
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ''
const to = newText[i] || ''
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({ from, to, start, end })
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update() {
let output = ''
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let { from, to, start, end, char } = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="dud">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
} else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
}
const phrases = [
'Hello!',
'ImHeather',
'IT Support & System Admin',
'Customer Service Expert',
'Tech Junkie',
const el = document.querySelector('.text')
const fx = new TextScramble(el)
let counter = 0
const next = () => {
fx.setText(phrases[counter]).then(() => {
setTimeout(next, 1000)
})
counter = (counter + 1) % phrases.length
}
next()
</script>
</body>
</html>

adding a score counter to an already existing game javascript

I am trying to expand on an already existing JavaScript project i coded along with by adding a score counter to a simple game where you control a GIF image with arrow keys, and collect a coin which randomly appears on the page. My attempts so far have been unsuccessful.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Coin Game Starter</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<h1 id= "scoreboard">0</h1>
<img id="player" src="https://media.tenor.com/images/0791eb3858075aca85eed5ecfe08c778/tenor.gif" alt="">
<img id="coin" src="coin.gif" alt="">
<script src="app.js"></script>
</body>
</html>
JS code:
function isTouching(a, b) {
const aRect = a.getBoundingClientRect();
const bRect = b.getBoundingClientRect();
return !(
aRect.top + aRect.height < bRect.top ||
aRect.top > bRect.top + bRect.height ||
aRect.left + aRect.width < bRect.left ||
aRect.left > bRect.left + bRect.width
);
}
const avatar = document.querySelector('#player')
const coin = document.querySelector('#coin')
window.addEventListener('keyup', function(e){
if(e.key === 'ArrowDown') {
const currTop = extractPos (avatar.style.top)
avatar.style.top = `${currTop + 50}px`
}
else if (e.key === 'ArrowUp'){
const currTop = extractPos (avatar.style.top)
avatar.style.top = `${currTop - 50}px`
}
else if (e.key === 'ArrowRight'){
const currLeft = extractPos (avatar.style.left)
avatar.style.left = `${currLeft + 50}px`
avatar.style.transform = 'scale(1,1)'
}
else if (e.key === 'ArrowLeft'){
const currLeft = extractPos (avatar.style.left)
avatar.style.left = `${currLeft - 50}px`
avatar.style.transform = 'scale(-1,1)'
}
if(isTouching(avatar, coin)) moveCoin ()
});
const moveCoin = () => {
const x = Math.floor(Math.random() * window.innerWidth);
const y = Math.floor(Math.random() * window.innerHeight);
coin.style.top = `${y}px`;
coin.style.left = `${x}px`;
}
const extractPos = (pos) => {
if(!pos) return 0
return parseInt(pos.slice(0,-2))
}
const score = document.getElementById('scoreboard')
const coinScore = score
function scoreUp () {
if (isTouching){
score ++
}
score.textContent = score
}
the bottom of the js page shows where i have tried to write a function that causes the score to increase upon the player grabbing the coin
you made the score variable a constant. change it to look like this and see if it works
let score = document.getElementById('scoreboard')
let coinScore = score
function scoreUp () {
if (isTouching){
score ++
}
score.textContent = score
}

javascript random gen nr + loops

I'm trying to make an program where it randomly picks 10 questions out of X questions(got 14 random ones written at the moment) without it picking the same questions again but i've been stuck for 4 hours on this junk.
My problem is with "randomNumbers()" function. This function generates random number (which marks the question respectively) and then checks if the numberArray already has generated number. If it doesnt, the number is supposed to be pushed to array.
I think I figured out the problem to be ## VERSION 1 ## for-loops if/else conditions. Any help ? :(
//edit, is while (true) correct way to handle this?
// dont mind ##VERSION 2## it was the first way I tried solving the problem.
(a lot of console logs to determine the bug :P )
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>Testimiskeskkond</title>
<!--<link rel="stylesheet" type="text/css" href="style.css"/> -->
<script src="scripts/jquery-2.1.4.min.js"></script>
<script src="scripts/js.js"></script>
</head>
<body>
<button onclick="startQuiz()">Alusta testimist</button>
<div id="question1"></div>
<div id=questions></div>
</body>
JAVASCRIPT
var amountOfQuestions = 11;
var questionCounter = 0;
var numberArray = new Array();
var questions = new Array();
questions[0] = 'Mitu kassi elab P2rnus?',
questions[1] = 'Mis on kassi nimi?',
questions[2] = 'Mida kass teeb?',
questions[3] = 'Millal kass syndis?',
questions[4] = 'Mitu hammast kassil on?',
questions[5] = 'Mitu kyynt on kassil?',
questions[6] = 'Mitu k6rva on kassil?',
questions[7] = 'Mis v2rvi on kass?',
questions[8] = 'Tooli v2rvus?',
questions[9] = 'Laua suurus?',
questions[10] = 'Lemmik jook?',
questions[11] = 'Lemmik s88k?',
questions[12] = 'Raamatupoe nimi?',
questions[13] = 'Viinapoe nimi?';
function startQuiz() {
var setQuestions = "";
while (questionCounter < amountOfQuestions) {
var random = randomNumbers();
console.log(random + "appppppi");
if (questionCounter < amountOfQuestions) {
setQuestions += questions[random] + "<br>";
questionCounter += 1;
} else {
setQuestions += questions[random];
questionCounter += 1;
}
}
$('#questions').html(setQuestions);
}
function randomNumbers() {
var arrLength = numberArray.length;
while (true) {
console.log(arrLength);
var randomNr = Math.floor(Math.random() * 14);
console.log(randomNr + " tereeeeeeeeee");
/*
######################
########### VERSION 1
######################*/
if (arrLength == 0) {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} else if (arrLength == 1) {
console.log("oooooooooooo");
if (numberArray[0] == randomNr) {
console.log("xxxxxxxxxxxxx");
break;
} else {
console.log("rrrrrrrrrrrrrrr");
numberArray.push(randomNr);
break;
}
} else {
for (var i = 0; i < arrLength-1; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
}
/*
######################
########### VERSION 2
######################
if (arrLength > 0) {
console.log("oooooooooooo");
for (var i = 0; i < arrLength; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
} else {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} */
}
return randomNr;
}
let selectionCount = 10;
let randomQuestions = [];
while(randomQuestions.length < selectionCount) {
let randomNr = Math.floor(Math.random() * questionList.length);
if(!randomQuestions.includes(randomNr)) {
randomQuestions.push(randomNbr);
}
}

slideshow with page numbers javascript

I have created slideshow. I want to add some description with page numbers.
I was trying to add function sliderText() to get result - "Image 1 of 7" etc.
I don't know what is wrong here. Can somebody give me some hints?
Thank you in advance,
Megi
var img_index = 0;
var imgs = [
"assets/1.jpg",
"assets/2.jpg",
"assets/3.jpg",
"assets/4.jpg",
"assets/5.jpg",
"assets/6.jpg",
"assets/7.jpg"
];
function findNextImage(isPrev) {
switch (true) {
case !!(isPrev && imgs[img_index + 1]):
img_index += 1
return imgs[img_index]
case !!imgs[img_index + 1]:
img_index += 1
return imgs[img_index]
default:
img_index = 0
return imgs[img_index]
}
sliderText()
}
function checkKey(event) {
if (event.keyCode == '39') {
document.getElementById("images").src = findNextImage();
} else if (event.keyCode == '37') {
document.getElementById("images").src = findNextImage(true);
}
}
document.onkeydown = checkKey;
function sliderText() {
var text = document.getElementsByClassName("slideshow_text");
var imageNumber = img_index + 1;
text.innerHTML = "image " + imageNumber + " of " + imgs.length;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
</head>
<h1 class="slideshow_text">Image 1 of 7</h1>
<img id="images" src="assets/1.jpg" />
<body>
</body>
<script src="test.js"></script>
</html>
Some modifications to improve code quality
I removed findNextImage which was not a pure function and introduced findNextImageIndex instead: findNextImageIndex neither accesses nor modifies any external variables and is thus easier to read. sliderText takes imgIndex as an argument so that you can easily see what parameters it needs to set the text.
Further suggestions
Consider moving the pre-set values Image 1 of 7 and "assets/1.jpg" from HTML to JavaScript as well. Initialize the slider with "assets/1.jpg" taken from the array and call sliderText(state.imgIndex); once initially.
Please notice that I moved the slide show HTML inside the <body> to make it valid HTML.
Modified code
var state = {
imgIndex: 0
};
var imgs = [
"assets/1.jpg",
"assets/2.jpg",
"assets/3.jpg",
"assets/4.jpg",
"assets/5.jpg",
"assets/6.jpg",
"assets/7.jpg"
];
function findNextImageIndex(imgIndex, isPrev) {
if(isPrev) {
if(imgIndex <= 0) {
return imgs.length - 1;
} else {
return imgIndex - 1;
}
} else {
if(imgIndex >= imgs.length - 1) {
return 0;
} else {
return imgIndex + 1;
}
}
}
function sliderText(imgIndex) {
var text = document.getElementsByClassName("slideshow_text")[0];
var imageNumber = imgIndex + 1;
text.innerHTML = "image " + imageNumber + " of " + imgs.length;
}
function goToNextImage(isPrev) {
state.imgIndex = findNextImageIndex(state.imgIndex, isPrev);
document.getElementById("images").src = imgs[state.imgIndex];
sliderText(state.imgIndex);
}
function checkKey(event) {
switch(event.keyCode) {
case 37: goToNextImage(true); break;
case 39: goToNextImage(false); break;
}
}
document.onkeydown = checkKey;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test</title>
</head>
<body>
<h1 class="slideshow_text">Image 1 of 7</h1>
<img id="images" src="assets/1.jpg" />
<script src="test.js"></script>
</body>
</html>

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'"

Categories