I can't get my html to execute my js file on Electron - javascript

I might be really bad at this but I've spent the last two hours on it so if someone could indicate me what's wrong I would be eternally grateful.
I am training on Electron and I am trying to make this game, Visual Novel style, that features dialogs, pictures and minigames. I am trying to set up the dialogs so that they may switch when the player presses "Space". To do that, I created a js file and tried to set it up, and I think the code should be working, but nothing happens when I press space... My best guess is that the app doesnt recognize the js file even tho the pathing should be good !
HTML:
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" />
<script src="blanche.js"></script>
<meta charset="UTF-8" />
<title>Hello World!</title>
<meta
http-equiv="Content-Security-Policy"
content="script-src 'self' 'unsafe-inline';"
/>
</head>
<body tabindex="0">
<section class="sprite">
<h1>sprite</h1>
</section>
<section class="score">
<h1>score</h1>
</section>
<section class="dialog" id="dialog">
<p id="text" class="text">Défaut</p>
</section>
<section class="loading">
<h1>loading</h1>
</section>
<section class="rps">
<h1>rps</h1>
</section>
</body>
</html>
CSS:
html, body{
height: 100%;
margin: 0;
}
h1{
margin: 0;
padding: 0;
}
body{
display: grid;
grid-template-rows: 42% 5% 25% 3% 25%;
gap: 0;
}
.sprite{
background-color: grey;
margin: 0;
padding: 0;
}
.score{
border-top: 3px black solid;
}
.dialog{
border-top: 3px black solid;
margin: 0;
padding: 0;
background-color: rgb(56, 53, 53);
}
.text{
color: green;
font-size: 1.3em;
font-weight: 500;
display: block;
}
.loading{
border-top: 3px black solid;
}
.rps{
border-top: 3px black solid;
}
JS:
const dialog = document.getElementById("dialog");
const text = document.getElementById("text");
let dialogueIndex = 0;
document.addEventListener("keydown", (event) => {
if (event.code === "Space") {
dialogueIndex++;
switch (dialogueIndex) {
case 1:
text.innerHTML = "Je vais bien, merci ! Et toi ?";
break;
case 2:
text.innerHTML = "Je vais bien aussi, merci !";
break;
case 3:
dialog.style.display = "none";
break;
default:
break;
}
}
});
I tried showing a console log at the very beginning of the js file, nothing happened. I verified the names of my files and their pathing 10 times, nothing looks wrong...

Solved, thank you ! I didnt see the message in the right console, in fact my js was trying to execute before my html was fully loaded, and so, my code couldn't target the element that didnt exist yet. As a solution, I added a window.onload = function() condition with my js, so that it would only activate once the page is loaded. thank you for helping !

Related

Load stylesheet with javascript and localStorage

I'm using a Jekyll website, doesn't really matter because this is a static page, I just write it as additional info.
Desired behavior:
I want to load my stylesheet via javascript, so it can depend of a local stored value, let's say dark and light.
I have done a little test of loading it by JS with the following code (which works).
GREEN
<head>
...
<link rel="stylesheet" href="/assets/css/{{'light'}}.css">
...
</head>
This loads the CSS file called "light" as expected.
But now I want to depend of the localStorage, with a variable theme that has light as value. I tried the following:
RED
<head>
...
<script>
var storedTheme = window.localStorage.getItem('theme'); //Tested and working in console
theme = storedTheme ? storedTheme : 'light'; //global variable (also readable in console)
</script>
<link rel="stylesheet" href="/assets/css/{{theme}}.css"> <!-- cant read global variable -->
...
</head>
Using global variables doesn't work, it gives me a 404 error as the stylesheet path is /assets/css/.css.
After that I thought that maybe creating an element would do the trick and I created one manually to test it:
RED
<head>
...
<p id="theme" style="display:none;">dark</p>
<link rel="stylesheet" href="/assets/css/{{document.getElementById('theme').innerHTML}}.css">
...
</head>
And nope, the path still appears as: /assets/css/.css
If you change styles on the <body> you get FOUC (Flash Of Unstyled Content). Try using a close equivalent like <main> and spread it 100% x 100% and <html> and <body> as well, but give them margin and padding of 0 in order to ensure <main> covers them completely.
The [disabled] attribute for the <link> is the best way of toggling them because they are still loaded but inert. Also, in the example there is a function called loadTheme(e) that is loaded on the 'DOMContentLoaded' event which insures that all of the DOM is loaded before hand. The example below will not work because localStorage is blocked on SO. There is a functioning example on Plunker. To test it:
Click the green Preview button.
Another frame should appear on the right. Within the frame is the webpage example click the ☀️ button.
It should be in dark mode now. Next, click the refresh ⟳ button located in the mini-toolbar within the frame or press ctrl+enter for Windows OS or ⌥+return for Mac OS.
The page should still be in dark mode. 👍
/* night.css
main {
background: #000;
color: #fff;
}
*/
/* default.css */
:root {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font: 1ch/1.5 'Segoe UI';
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-size: 4ch;
}
main {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
color: #000;
}
form {
width: 80vw;
margin: 20px auto;
}
fieldset {
width: max-content;
min-height: 25px;
margin-left: auto;
padding: 0 1.5px 1.5px;
border-radius: 8px;
background: inherit;
color: inherit;
}
button {
display: block;
width: 100%;
height: 100%;
border: 0;
font-size: 4rem;
text-align: center;
background: transparent;
cursor: pointer;
}
#theme::before {
content: '☀️';
}
.night #theme::before {
content: '🌙';
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='lib/default.css' rel='stylesheet'>
<link class='night' href='lib/night.css' rel='stylesheet' disabled>
<style></style>
</head>
<body>
<main>
<form id='UI'>
<fieldset name='box'>
<legend>Theme</legend>
<button id='theme' type='button'></button>
</fieldset>
<p>Click the "Theme" switch to toggle between `disabled` `true` and `false` on `night.css` and `light.css` `
<link>`s.</p>
</form>
</main>
<script>
const UI = document.forms.UI;
const M = document.querySelector('main');
const L = document.querySelector('.night')
const switchTheme = e => {
const clk = e.target;
if (clk.matches('button')) {
M.classList.toggle('night');
L.toggleAttribute('disabled');
}
let status = M.className === 'night' ? 'on' : 'off';
localStorage.setItem('theme', status);
};
const loadTheme = e => {
let cfg = localStorage.getItem('theme');
if (cfg === 'on') {
M.classList.add('night');
L.removeAttribute('disabled');
} else {
M.classList.remove('night');
L.setAttribute('disabled', true);
}
};
UI.addEventListener('click', switchTheme);
document.addEventListener('DOMContentLoaded', loadTheme);
</script>
</body>
</html>

Why doesn't this code display the button after I hide it?

When I run this JavaScript code, button2 doesn't get displayed again. I'm not sure why this is happening. I am trying to use this in a game I am creating. I searched this up on Google multiple times and couldn't find an answer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2"></button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "auto";
}
</script>
</html>
A good way to handle this and provide more reusable code is to use <element>.classList.remove() and <element>.classList.add() to set or unset a hidden class. This can also be useful for toggling with <element>.classList.toggle().
This has the added advantage of being able to set your default display style in the CSS rather than burying it in the javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
/* allows setting preferred display in CSS */
display: block;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn1" onclick="toggleBtn2()">
Toggle Button 2
</button>
<button class="btn2 hidden" id="btn2">Button 2</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.classList.remove("hidden");
}
function toggleBtn2() {
btn2.classList.toggle("hidden");
}
</script>
</html>
There is no auto display is CSS. As tarkh mentioned in his answer, display block would insert the new button below the initial button, and other display options would have other behaviors. But the display property does not have a value auto.
This may be my opinion, but I think modern websites shouldn't use the onclick function for events. We should separate our HTML, JS and CSS. This helps with reusability. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
So I would create a solution that uses an event handler in the Javascript. Something like:
window.onload = function(){
const btn2 = document.getElementById("btn2");
const btn1 = document.getElementsByClassName("btn1");
for(let i = 0; i < btn1.length; i++) {
btn1[i].addEventListener('click', function(){
btn2.style.display = "block";
})
}
}
Maybe btn2.style.display = "block";?
Or, as #charlietfl added, btn2.style.display = "inline"; since that is what browser default is for a button
display: block means that the element is displayed as a block, as
paragraphs and headers have always been. A block has some whitespace
above and below it and tolerates no HTML elements next to it, except
when ordered otherwise (by adding a float declaration to another
element, for instance).
display: inline means that the element is displayed inline, inside the
current block on the same line. Only when it's between two blocks does
the element form an 'anonymous block', that however has the smallest
possible width.
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">new button here</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "block";
}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">Button 2</button>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "inline";
}
</script>
</body>
</html>
Use display = inline or block instead of auto.
Add some text content to button 2 like this:
<button class="btn2" id="btn2">Button 2</button>
CSS: "display: auto;"?
display does not have an auto attribute.
you can try "inline" or "block".
'''
function showBtn2() {
btn2.style.display = "inline";
}
'''
Try using
btn2.style.display = "block";
for your script because css display doesn't have that kind of attribute you
you can read it more here : more
you'll see there's no such thing as display:auto

.css file, ::first-line not possible. how to achieve this? Ubuntu 18.04

Ubuntu 18.04
i am customizing the panel, this is the content in .css file
i have added ::first-line part to cusomize first line as shown in the below image. but it is not applied after reboot.
Content of .css file:
#panel .clock-display {
color: blue; }
#panel .clock-display::first-line {
color: green; }
Content of .js file:
var DateMenuButton = new Lang.Class({
Name: 'DateMenuButton',
Extends: PanelMenu.Button,
_init() {
let item;
let hbox;
let vbox;
let menuAlignment = 0.5;
if (Clutter.get_default_text_direction() == Clutter.TextDirection.RTL)
menuAlignment = 1.0 - menuAlignment;
this.parent(menuAlignment);
this._clockDisplay = new St.Label({ y_align: Clutter.ActorAlign.CENTER });
this._indicator = new MessagesIndicator();
let box = new St.BoxLayout();
box.add_actor(new IndicatorPad(this._indicator.actor));
box.add_actor(this._clockDisplay);
box.add_actor(this._indicator.actor);
this.actor.label_actor = this._clockDisplay;
this.actor.add_actor(box);
this.actor.add_style_class_name ('clock-display');
in this last line this.actor.add_style_calss_name ('clock-display'); i guess i have to specify its pseudo_calss or something but i dont have any idea.
in the below image if you see the day with time stamp, it is the default behavior when Ubuntu is freshly installed.
by using Clock Override Extension, it is possible to make our own text..
like in this image..
here is a clue, this Clock Override Extension have special feature to make a next line by adding %n in its settings https://developer.gnome.org/glib/stable/glib-GDateTime.html#g-date-time-format
Clock Override Extension Details: https://extensions.gnome.org/extension/1206/clock-override/
Question:
i am looking to configure both lines independently in .css file to choose the colors, heights, weights, shadows, borders etc.
is it achievable?
all related files here:
https://wetransfer.com/downloads/dd97a53972b17f746225efdfa345a03220181231063516/111ced
Can you try to add a style class to a specific object?
For example: #line 475
this._clockDisplay = new St.Label({ y_align: Clutter.ActorAlign.CENTER, style_class: 'clock-label' });
CSS:
.clock-label { color: #101010; font-weight: bold; background: #fff; }
Try it.
It is working unless your text is considered as one line.
#panel .clock-display {
color: blue;
margin-left: 40px;
margin-right: 40px;
}
#panel .clock-display::first-line {
height: 40px;
width: device-width;
background: blue;}
.barfont {
height: 30px;
width: device-width;
color: blue;
font-size:15px;
font-weight: bold;
line-height:0px;
}
.barbackground {
margin: 0;
padding: 0;
height: 30px;
width: device-width;
background-color: green;
border-top-style: solid;
border-top-color: green;
line-height:0px;
}
<html>
<body background="https://i.stack.imgur.com/80hPG.png" >
<div class="barbackground">
<p class="barfont">data &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp day first link </p></div>
</body>
</html>
Changing the first line.
.clock-display {
color: blue;
margin-left: 40px;
text-indent: 40px;
}
::first-line {
color: green;
/* WARNING: DO NOT USE THESE */
/* Many properties are invalid in ::first-line pseudo-elements */
margin-left: 20px;
text-indent: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body >
<pre class="clock-display">
121
data and time</pre>
</body>
</html>

Save contentEditable into html file with javascript

How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable

After auto scroll to bottom of div, enable user to scroll back up?

There are a large number of this question floating around this site. None of them seem to help me though. I am trying to code a text based browser game using javascript and jQuery, as a base to build my knowledge of coding.
I have a javascript code:
window.setInterval(function(e) { //This function is the only way to get the scroll to bottom to work, for me.
e = document.getElementById('console'); //'console' is the area that outputs the system text, after a user answers questions.
e.scrollTop = e.scrollHeight - e.clientHeight; //It works without the '- e.clientHeight', but I read that this is proper.
});
For the scroll to bottom function, this works very well, but how in the world do I allow the user to scroll up... to review what has transpired?
I haven't found a question asked in this fashion, so I don't believe it is a duplicate. If so, I guess I'll keep searching.
-Edit-
Okay... I guess my description wasn't descriptive enough, so let me try to fix that.
Here is a snipit of the first bit of my code (I know it isn't set up the best right now, but that is why I'm learning):
Javascript/JQuery
window.setInterval(function(e) { //'#console' scrolls to bottom <-- how do I let the user scroll up to review?
e = document.getElementById('console');
e.scrollTop = e.scrollHeight - e.clientHeight;
});
onkeyup = (function(e) { //On <enter> erase data in the ("input")
if (e.keyCode == 13) {
$("input").val("");
e.preventDefault();
return false;
}
});
$(document).ready(function() {
$("#console").fadeIn(3000); //A console to output answers and scenarios to
$("form").submit(function() { //User input
var input = $("#command_line").val(); //A nifty box to put your answers in
var check = false;
function check() { //If you don't follow directions this happens
check = true;
}
//startup
var yes = false;
var no = false;
currentarea = "Start";
function start() {
while (yes != true && no != true && currentarea == "Start") {
if (input == "yes") {
yes = true;
$("<p>Great! What is your gender? Type <u><b>m</b></u> for Male or <u><b>f</b></u> for Female.</p>").hide().insertBefore("#placeholder").fadeIn(1000);
clothes = s_clths;
document.getElementById("clothes").innerHTML = clothes;
currentarea = "Gender Assignment";
check();
return currentarea;
}
}
start();
});
So, basically, after getting the scroll to bottom working, I noticed users might want to scroll up to see what previous statements said. Right now, they cannot scroll up. If I need to make another code all together that is okay, but I cannot find one that will work for me. I've tried every suggestion I could find from all the relative postings, with no success. I have been at this for about twelve hours now, and can't figure it out by myself.
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="scripts/jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="banner">
<p>Welcome To ! An Epic Journey Awaites You!</p>
</div>
<div id="console_wrapper">
<div id="console">
<p id="Start">Would you like to begin your adventure? Type <u><b>yes</b></u> or <u><b>no</b></u>.</p>
<p id="message_help" style="display: none;">Some help, if you need it.</p>
<!--
PLACEHOLDER: THIS IS WHERE YOUR CHOICES ARE INPUTED
-->
<div id="placeholder"></div>
</div>
</div>
<form id="form" onsubmit="return false;">
<input type="text" size="50" autofocus="autofocus" autocomplete="off" id="command_line" />
</form>
<script type="text/javascript" src="scripts/game.js"></script>
</body>
</html>
CSS
#banner {
width: auto;
background-color: maroon;
border-style: ridge;
border-width: 5px;
border-color: grey;
text-shadow: 2px 2px orange;
}
#console_wrapper {
border-style: ridge;
border-width: 3px;
border-color: grey;
max-height: 150px;
margin: 75px auto;
margin-top: 12px;
width: 44%;
}
#console {
display: none;
height: 150px;
text-align: center;
margin-top: 0px;
overflow-y: scroll;
}
#command_line {
font-family: Times New Roman;
font-size: 14px;
border-style: ridge;
border-color: blue;
border-width: 4px;
margin: auto;
}
body {
background-color: black;
border-style: ridge;
border-width: 5px;
border-color: red;
width: 90%;
max-height: 900px;
margin: auto;
}
The answer to my question was:
$("#console").animate({ scrollTop: "999999999px" }, 'slow'); //Scroll the console to the bottom.

Categories

Resources