1

Everyday my teacher looks across the internet to find random facts for us then she writes on the board and we get to see it each day we go in her class. I'm trying to make a super simple website that once a button is clicked an alert at the top of the page appears. Whenever the fact I cant figure out how to make the console go to the alert. I've looked at a different other Stack question but i didn't really understand it. Here is my complete code. I'm sorry i just started javascript and literally couldn't be more new to it. Thanks in advance!

const express = require("express");
const app = express();
app.use(express.static("public"));
app.get("/", (request, response) => {
  response.sendFile(__dirname + "/facts.html");
});
const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

var fact = require('random-fact');
fact();
<!DOCTYPE html>
<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">
    <title>Generate Random Facts</title>
</head>
<body>
<h1>Fact Generator</h1>
<br><br><br><br>
<script>

function test() {
    alert('fact');
}

</script>
<input type="button" onclick="test()" value="Generate Random Fact!">
</body>
</html>

8
  • 1
    The JavaScript in your top box is node.js code that runs on the server. It can't alert in the browser. Commented Feb 9, 2021 at 2:20
  • Ohhh :(. Well it is possible to display in a box on the page? Commented Feb 9, 2021 at 2:23
  • Not with console.log(). You should use AJAX. Commented Feb 9, 2021 at 2:24
  • I have no idea what that is...Ummm is it easy? Commented Feb 9, 2021 at 2:25
  • 1
    Not if you're a total beginner. Commented Feb 9, 2021 at 2:28

2 Answers 2

2

I'm sorry if I'm not understanding your code properly but from my understanding the first code block, the NodeJS is sending a file on the root url. That root file is what you want to alert this "random fact"

However, the random fact data is stored in var fact = require("random-fact")

NodeJS is a JavaScript runtime environment. Meaning a place to execute JavaScript code, OUTSIDE the browser and in the server. NodeJS isn't like vanilla JS where you have access to the BOM and DOM.

However, with express you can set up what's called an endpoint. That endpoint will send the data on each request to each route which you can set up on the front end.

First off, I'm assuming the fact() function returns some data. We'll set up an endpoint:

app.get('/random-facts', (req, res) => res.send(fact()));

whenever we send a get request to /random-facts it'll execute the function and hopefully get what you want

On the frontend we need to do what's called an AJAX request. Where you send a request to the API. Like you do in your browser when you type www.google.com you send a get request. AJAX request can get more sophisticated with just GET requests but that's for something else.

We'll do that with JS using the fetch API

On your html you can do

<script>
fetch('http://localhost:3000/random-facts')
  .then(response => response.json())
  .then(data => alert(data));
</script>

This is probably a bit more advanced than what you know but I hope this helps

Sign up to request clarification or add additional context in comments.

1 Comment

"This is probably a bit more advanced than what you know but I hope this helps" yes, yes it is. Honestly i just started javascript yesterday so its gonna take me a minute for this. Thanks though!
1

Like someone else said, the JavaScript you have up there is server side NodeJS.

Instead, just use your HTML and statically host it on GitHub or something.

Here is an example of a random fact from a list of facts:

<!DOCTYPE html>
<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" />
        <title>Generate Random Facts</title>
    </head>
    <body>
        <h1>Fact Generator</h1>
        <p id="fact"> </p>
        <script>
            // populate with multiple facts
            var facts = ["fact one", "fact two", "fact three", "fact four"];

            function alertFact() {
                const fact = returnFact()
                
                document.getElementById('fact').innerText = fact
                alert(fact);
            }

            function returnFact() {
                var fact = facts[Math.floor(Math.random() * facts.length)];

                return fact;
            }
        </script>
        <input type="button" onclick="alertFact()" value="Generate Random Fact!" />
    </body>
</html>

or you can view it here: https://jsfiddle.net/utdoLbj2/

10 Comments

Thanks much man! This works great. The only issue is i have to input each one my self but that's just because i'm a little lazy :D Right now i have 30 facts but soon i will have 3090 facts. LOL
What format are the facts in? You could pretty easily write a script to format them into the needed array.
That would be amazing! this is the github with all the facts.
@moneymike here is the facts sorted into an array: github.com/mr-winson/so-helper/blob/master/facts/… It also includes the JavaScript file to reformat any new facts. If you dont mind, give me a follow on github too!
That’s awesome! Glad I could help!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.