Why is require('fs') causing my js variables to not show in html? - javascript

I'm trying to make an electron app that increments and reduces a number and updates that number to a local .txt file.
I have the numbers displaying and counting up/down but as soon as I introduce the fs node it reverts to the placeholder text of "ScoreA"
var fs = require('fs');
//Score A initialise
var scoreAOriginal = 0;
var dx = scoreAOriginal;
//Score A button functions
function incA(num){
dx = dx + num;
}
function decA(num){
if (dx >= 1){
dx = dx - num;
}
}
//Score B initialise
var scoreBOriginal = 0;
var dy = scoreBOriginal;
//Score B button functions
function incB(num){
dy = dy + num;
}
function decB(num){
dy = dy - num;
}
// Refresher and value assignment to div classes in index.html
setInterval(function(){ document.getElementById("scoreA").innerHTML = dx; document.getElementById("scoreB").innerHTML = dy; }, 100);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Peppy - by Doug</title>
<script src="./main.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<h1>Peppy</h1>
<div class="scoreConsoles">
<div>
<button class="button button5" onclick="incA(1)">+</button>
<div id="scoreA">scoreA</div>
<button class="button button5" onclick="decA(1)">-</button>
</div>
<div>
<button class="button button5" onclick="incB(1)">+</button>
<div id="scoreB">scoreB</div>
<button class="button button5" onclick="decB(1)">-</button>
</div>
</div>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>

How did you create the window? You know you need to enable node integration:
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});

Related

Github Pages as Static Image Hosting

I am trying to use GitHub pages to host static images for a website I am working on. The website randomizes div locations across the page, and it's supposed to use the photos from the repository. Here is the repository that is hosting the images.
The issue is that the images are not loading from the Github pages. Am I not referencing the photos correctly in the Javascript? Here is a photo that shows what the page looks like when I run it. As you can see, none of the images load into the webpage. Not sure if I am referencing the photo incorrectly in the JS, or if I need to add any HTML code to reference the photos. Either way, I would really appreciate any help. :)
HTML:
<!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>page</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<!-- <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> -->
</head>
<body>
<h1><b>Issy B. Designs</b></h1><br>
<div class="random"></div>
</body>
</html>
JS:
const imgPoss = [];
let maxX, maxY;
function placeImg() {
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const randImg = Math.random() * NUM_OF_IMAGES;
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';
const {random: r} = Math;
const x = r() * maxX;
const y = r() * maxY;
if(!isOverlap(x,y)) {
var link = `<img class="random" style="left: ${x}px; top: ${y}px;" src="${imgSrc}" />`;
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = bodyHtml + link;
imgPoss.push({x, y}); // record all img positions
}
}
function isOverlap(x, y) { // return true if overlapping
const img = {x: 128, y:160};
for(const imgPos of imgPoss) {
if( x>imgPos.x-img.x && x<imgPos.x+img.x &&
y>imgPos.y-img.y && y<imgPos.y+img.y ) return true;
}
return false;
}
onload = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
setInterval(placeImg, 10);
}
onresize = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
}
In JavaScript Math.random() returns float between 0 and 1. By multiplying it by 90 you get a float, but all your photos are intigers. And since your pictures start from 10.png it should look like this
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const START_OF_IMAGES = 10;
const randImg = Math.round(Math.random() * NUM_OF_IMAGES + START_OF_IMAGES);
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';

Got a persistent change font size slider in Jquery but need help to turn into Vanilla js

Now I have this Jquery font rezising slider but need it in vanilla.js. It is working properly but I can not manage turning it into plain Javascript.
My code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1" />
</div>
<div>
<h1>Changing Font Size</h2>
<p>I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
<script>
var curSize = localStorage.getItem("saveSize");
if (curSize) {
var saveSize = curSize;
$('body').css('font-size', saveSize + 'px');
var setSize = $('body').css('font-size');
}
$('.font-slider input[type="range"]').on("input change", function () {
var newSize = $(this).val(),
defaultSize = $("body").css("font-size"),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
$("body").css("font-size", newSize + "px");
localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>
Try:
var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
if (curSize) {
var saveSize = curSize;
body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function (e) {
var newSize = this.value,
defaultSize = body.style.getPropertyValue('font-size'),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
body.style.fontSize = newSize + 'px';
localStorage.setItem("saveSize", newSize);
}
});

Javascript: code with no animation with requestAnimationFrame?

I am learning Javacript and test the code from the book (below). It should animate an image but doesn't. I add print out using alert which shows that the function is executed only once. What goes wrong?
<!doctype html>
<html>
<head>
<title> My home page </title>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
//alert(count);
//++count;
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time ;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
</script>
</head>
<body>
<p style ="text-align: center">
<img src ="img/cat.jpg" style ="position: relative">
</p >
</body>
<script>requestAnimationFrame(animate);</script>
</html>
Thank you for the help.
If you look at the console, you will see that the cat is undefined.
This happens because var cat = document.querySelector("img"); is run in the head element and so the img does not exist yet.
If you move the code at the end of the body it will work.
Or you could run your code when the DOMContentLoaded event is fired.
<!doctype html>
<html>
<head>
<title> My home page </title>
</head>
<body>
<p style ="text-align: center">
<img src ="img/cat.jpg" style ="position: relative">
</p >
</body>
<script>
var cat = document.querySelector("img");
var angle = 0, lastTime = null;
var count = 0;
function animate(time) {
//alert(count);
//++count;
if (lastTime != null)
angle += (time - lastTime) * 0.001;
lastTime = time ;
cat.style.top = (Math.sin(angle) * 20) + "px";
cat.style.left = (Math.cos(angle) * 200) + "px";
requestAnimationFrame(animate);
}
</script>
<script>requestAnimationFrame(animate);</script>
</html>
When the browser see a <script> tag, he stop rendering the page, and run the code inside.
So, the problem in the code that the line var cat = document.querySelector("img"); happen before the img is append to the document, so you query get nothing.
the only change you need to do- is to move the var cat = document.querySelector("img"); to under the body, like so:
</body>
<script>
var cat = document.querySelector("img");
requestAnimationFrame(animate);
</script>
</html>

unexpected token error line 41-"y:Math.round(Math.random()*(h-cw)/cw);"

I am trying to re-create the classic mobile game "Snake" using HTML/CSS3 and Javascript. When I run what I have in chrome I get the unexpected token error on line 41. Why is the semi-colon unexpected? The code I have so far is below.
$(document).ready(function(){
//define vars
var canvas = $('#canvas')[0];
var ctx = canvas.getContext("2d");
var w = canvas.width();
var h = canvas.height();
var cw = 15;
var d = "right";
var food;
var score;
var speed = 130;
//Snake Array
var snake_array;
//initalizer
function init(){
create_snake();
create_food();
score = 0;
if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, speed);
}
init();
function create_snake(){
var length = 5;
snake_array =[];
for(var i = length-1;i >=0;i--){
snake_array.push({x: i,y :0});
}
}
//Create Food
function create_food(){
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- line 41
};
}
});
HTML CODE
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="container">
<div id ="overlay">
Your final score: <span id = "final_score">
</span>
<br>
<a onclick="window.location.reload()" href="#">Click to play again!</a>
</div>
<canvas id="canvas" width="600" height="400">
</canvas>
<div id="stats">
<div class="score"></div>
<div class="score"></div>
<button onclick="resetScore()" id="reset_score">Reset high score</button>
</div>
</div>
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Main JS -->
<script src="C:\Users\student\Desktop\SnakeGame\script.js"></script>
</body>
</html>
When defining a variable like this x: (typically used in objects) you cannot put a ; after the last defined variable like you did:
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- remove this semi-colon
};
Do this instead
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw)
};
I hope I was to any help :3

How do I separate two svgs using raphaƫl?

I'm a beginner beginner. I can get the behavior that I want to occur, but instead of occurring in two separate SVGs, all the behavior is occurring in 'svg2' although I have selected the respective ids for 'svg1' and 'svg2' (or at least I think I did)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.0/raphael-min.js"></script>
<script src="logic.js"></script>
<title>Forms and Concentric Circles</title>
</head>
<body>
<h1>Forms and Concentric Circles</h1>
<div id="svg1"></div>
<div class="form">Add how many?
<input type="text" id="howmany" />
<button id="more">Add More</button></div>
<div id="svg2"></div>
<div class="form">
<button id="another">Add Another</button>
</div>
</body>
</html>
var paper;
disappear = function() {
this.remove();
}
spin = function(r) {
angle = Math.random()*1440 - 720;
initial = { 'transform': 'r0' }
final = { 'transform': 'r' + angle}
r.attr(initial);
r.animate(final, 2000);
}
addMore = function() {
rectNum = $('#howmany').val();
for (step = 0; step < rectNum; step += 1) {
x = Math.random() * 180;
y = Math.random() * 180;
r = paper.rect(x, y, 20, 20);
filled = {
'fill': '#ddf'
}
r.attr(filled);
r.click(disappear);
spin(r);
}
}
radius = 10
morecircles = function() {
paper.circle(100, 100, radius);
radius = radius + 10;
}
setup = function() {
paper = Raphael('svg1', 200, 200);
$('#more').click(addMore);
paper = Raphael('svg2', 200, 200);
$('#another').click(morecircles);
}
$(document).ready(setup);
change the name for the second svg for example
paper2.circle
and in your setup function it should be
paper2.Raphael('svg2',200,200)

Categories