Reputation: 163
I am still trying to get my head around what's possible with frontend vs backend. I still don't understand how to incorporate the likes of an eventListener into my app when I can't select the document.
I have created a script.js file and added it to my public directory:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hours Calculator</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/391e6a689e.js" crossorigin="anonymous"></script>
<script src="/script.js"></script>
</head>
<body>
and I am serving this folder/files in my app.js like so:
app.use(express.static(__dirname + '/public'));
However I am unable to target anything in my script.js, for example:
let h1 = document.body.querySelector('h1');
h1.style.color = 'brown';
Doesn't work. h1 is undefined.
I am sure there is an extremely straight forward explanation but there are some gaps in my understanding and would like if someone can explain to me why this isn't working and how I can get the front end and the back end interacting.
Upvotes: 0
Views: 2055
Reputation: 2365
The Node.js "events" module and the "EventEmitter" module facilitates communication between objects in Node. The EventEmitter module is at the core of Node's asynchronous event-driven architecture. Here is how you can create custom events and emit them:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
//Event Listener
const EventListenerFunc = () => {
console.log('an event occurred!');
}
//Registering the event with the listener
myEmitter.on('eventName', EventListenerFunc);
//Emitting the event
myEmitter.emit('eventName');
Javascript is a Scripting language. It is basically used on the client-side. JavaScript can run in any engine like JavaScript Core (Safari), Spider monkey (Firefox), V8 (Google Chrome). NodeJS is a Javascript runtime environment. NodeJS code can be run outside the browser. It is mostly used on the server-side. Node.js only runs in a V8 engine that is mainly used by Google Chrome. Nodejs comes with a lot of modules and mostly used in web development. Node.js makes the Javascript more powerful and adds many great features to it.
Node.js does not provide a built-in DOM, so you can't access document object in Node.js and there are several modules which can construct a DOM from a string of HTML source code. Two popular DOM modules are cheerio and jsdom. You can make use of these modules to have an access to DOM level manipulation of the data in your code.
Upvotes: 1