sorry for this very basic question.
So I want to know how to make buttons responsive.
I have a client.js and index.html as shown below
// Function to change the content of t2
function modifyText() {
const t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// Add event listener to table
const el = document.getElementById("myButton");
el.addEventListener("click", modifyText, false);
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
<button id="myButton">Click Me!</button>
When I run on codepen it works fine.
But when I try to run these locally, with a server.js like this
console.log('Server-side code running');
const express = require('express');
const app = express();
// serve files from the public directory
app.use(express.static('public'));
// start the express web server listening on 8080
app.listen(8080, () => {
console.log('listening on 8080');
});
// serve the homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
and I change the html into having a script calling the client.js
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Example-1</title>
</head>
<body>
<button id="myButton">Click me!</button>
<table id="outside">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
<script src="client.js"></script>
</table>
</body>
</html>
Then I run node server.js and I type localhost:8080 in my browser, the html file gets displayed but when I click the button, it doesn't cause any number changes.
How can I get these to work for real?
Also, ultimately I want the node.js server side to know a button has been pressed. Maybe print on the node.js console that "a button was pressed", whenever it was done on my browser. How can I achieve that?
What I want is to pass information from client side to server side easily but I am quite confused with how to do that and many people suggest different ways.
Edit:
Aligned file names.
Related
I have a very simple assignment for my school, but I just can't figure out how to solve it.
I need to create an endpoint for an API in Node.JS that responds to a GET request - so when I click the button in my HTML file, it should call my API endpoint and print the message "Hello World" and the number of times it has been called in an alert box.
UPDATED, UPDATED:
client/index.html
<html>
<head></head>
</body>
<!--
When clicking this button, an alert needs to show up
displaying a GET request from the server.js file with
the text "Hello World" a long with a number increasing
for each time, the call has been made
-->
<button id="myBtn" type="button" onclick="alertCount()">Send</button>
<script src="js/javascript.js"></script>
</body>
</html>
client/javascript.js
function alertCount() {
fetch("http://localhost:3000").then(res => {
console.log("log");
return res.text()
}).then(text => {
alert(text)
})
};
server/server.js
const express = require('express');
const app = express();
const port = 3000;
let counter = 0;
app.use(express.static('client'));
app.get('/', (req, res) => {
res.send('"Hello World!" has been called ' + counter + ' time(s).');
++counter;
});
app.listen(port, () => console.log("Listening..."));
You need to add a function in the onclick handler of the button. See an example here
// javascript.js
function myFunction() {
fetch("https://5f7203e364a3720016e61337.mockapi.io/text").then(res => {
return res.text()
}).then(text => {
alert(text)
})
}
<!-- index.html -->
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script src="javascript.js"></script>
EDIT: updated the script, all you need to do is replace the url inside the fetch()
I have node js running a server that loads an html file with express. This html file has javascript that hides and shows a picture on the page with a button. I want to use the same function to hide and show the picture without the need for a button by calling the method in the main.js file that contains the rest of the application code. However, whenever I call the method it gives me a document not defined error. The button that calls the same function when clicked works however. I am not sure what the problem is (new to node).
web.js:
const hider = require("./public/script");
function site(){
const express = require('express');
const path = require('path');
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => console.log("Server Started on: 127.0.0.1:"+port));
};
function hidePic(){
hider.hide();
}
module.exports = { site , hidePic}
File loaded by express. The button to hide the image works.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="hide()">Try it</button>
<div id="picture1">
<img src="img.jpg" alt="img">
</div>
<script src="script.js"></script>
</body>
</html>
script.js:
function hide() {
var x = document.getElementById("picture1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
module.exports = { hide }
Main program
main.js:
const web = require("./website")
web.site();
web.hidePic(); //Want this to hide picture in on webserver from within this file
I'd like to transmit a variable to another page with Node, in order to use it in the other page, I tried localstorage and defining a global variable, but no result for the moment, it says that node can't access the localstorage of the window :
test.js
var express = require('express')
var session = require('express-session')
var app = express()
app.post('/test1.html', function(req, res){
var user = "Jonhy DEEPPP";
console.log(user);
res.render( 'test1.html', { user:user } );
});
test1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Titre</title>
</head>
<body>
<script>
alert(user);
</script>
</body>
</html>
I want to test the new Firefox Storage Access API to allow 1st party storage (cookie, local storage, indexeddb, ...) to an iframe of a different domain (but still under my control).
Parent Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://child.local:8080/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
</script>
</body>
</html>
Child Iframe Markup / code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
When clicking on the "Login" button from the Child Iframe, the following log output is generated:
no access - requesting access # iframe-firefox.html:22:25
hasAccess: true # iframe-firefox.html:27:25
Request to access cookie or storage on “http://child.local:8080/iframe-firefox.html” was blocked because we are blocking all third-party storage access requests and content blocking is enabled. # iframe-firefox.html:28:24
The visible conclusion is:
The promise document.hasStorageAccess() resolves
The hasAccess parameter is initially 'false'
The promise of document.requestStorageAccess() is returned and resolves
The 2nd promise document.hasStorageAccess() resolves
The hasAccess parameter is now 'true'
nevertheless, simple storage access to local storage is not possible.
What do I do wrong?
More Info's:
Firefox Developer Edition Version 65.0b9
Content Blocking Setting:
This seems to be a bug in the version of Firefox you're using. I set up a test locally of what you have and in Firefox 69.0.1 (64 bit), I get no error and the value is stored to local storage. When I took the sandbox flag allow-storage-access-by-user-activation out of the parent iframe, the child failed to get permission for local storage, so that confirms that my setup was actually working properly. Here's what I did:
Created a Node.js/Express server for the parent:
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8080, function() {
console.log('listening on *:8080');
});
Created a Node.js/Express server for the child (with different port to trigger same origin policy):
const express = require('express');
const cors = require('cors');
const path = require('path');
const server = express();
server.use(cors());
server.use(express.static(path.resolve('./public')));
server.listen(8081, function() {
console.log('listening on *:8081');
});
Created an index.html for the parent (pretty much the same as yours):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Parent Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<div>
Cookies: <ul class="cookie-data"></ul>
</div>
<iframe
id="rpc-gateway"
src="http://127.0.0.1:8081/iframe-firefox.html"
sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin"></iframe>
<script type="text/javascript">
var chan = Channel.build({
window: document.getElementById("rpc-gateway").contentWindow,
origin: "*",
scope: "testScope"
});
// Added this to try out the JSChannel
chan.call({
method: "reverse",
params: "hello world!",
success: function(v) {
console.log(v);
}
});
</script>
</body>
</html>
And created iframe-firefox.html for the child:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Child Domain</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jschannel/1.0.0-git-commit1-8c4f7eb/jschannel.min.js"></script>
</head>
<body>
<button onClick="onLoginClick()">Login</button>
<script type="text/javascript">
var chan = Channel.build({
window: window.parent,
origin: "*",
scope: "testScope"
});
// Other end of the JSChannel call
chan.bind("reverse", function(trans, s) {
return s.split("").reverse().join("");
});
let onLoginClick = function(trans, params) {
document.hasStorageAccess().then(hasAccess => {
if (!hasAccess) {
console.log("no access - requesting access");
return document.requestStorageAccess();
}
}).then(_ => {
document.hasStorageAccess().then(hasAccess => {
console.log("hasAccess:", hasAccess);
window.localStorage.setItem('foo', 'bar');
})
}).catch((err) => {
console.log("hasStorageAccess() failed", err);
});
};
</script>
</body>
</html>
And everything worked as expected... So I'm feeling pretty sure that the issue is with the specific version of Firefox Developer Edition that you're using.
Also, here's a link to a zip of my setup if you want to give it a try on your end and see if this works differently than what you have: server.zip
Let me know if there's anything else I can do to help.
im very new to Angular.js and i cant seem to get my expression to display the values from my controller, it just sees it as a string when i view it. i have no idea why. Am i missing something super obvious?, any help would be appreciated.
Im also using node.js just to set up my local server, but i dont believe this is the problem.
var appdemo = angular.module('appdemo', []);
appdemo.controller('ctrl', function($scope) {
$scope.value1 = 1;
$scope.value2 = 2;
$scope.updateValue = function() {
$scope.x = $scope.value1 + ' x ' + $scope.value2 +
" = " (+$scope.value1 + +$scope.value2)
};
});
<!DOCTYPE html>
<html ng-app="appdemo">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>appdemo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div ng-controller="ctrl">
<span>times</span>
<input type="text" ng-model="value1" />
<input type="text" ng-model="value2" />
<button ng-click="updateValue()">total</button> {{x}} {{ value1 }}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script src="main.js"></script>
</body>
</html>
this is my local server not entirely convinced if done it correctly.
const express = require('express')
const app = express()
app.use(express.static("public"))
app.engine("html", require("ejs").renderFile)
app.set("view engine", "html")
app.set("views", "./views")
app.get("/", (req, res) =>{
res.render("index")
})
app.listen(3000, ()=>{
console.log("Running on port 3000...")
})
file structure:
node_mdodules
public
css
views
index.html
main.js
app.js
package-lock.json
package.json
Let assume you have the next folder structure:
-App name
-public
-html
-index.html
-js
-main.js
-style.css
-server.js //Or any other name for your node js server
In your server js you should use the __dirname property:
app.use(express.static(__dirname + '/public'));
Then in your html replace your import script for this:
<script src="/js/main.js"></script>