Random name generator html

How to build a simple Javascript name generator

In honour of World Book Day (warning, horrible web design), I thought I would create a nice web tool for mashing up words into generic, and hopefully occasionally amusing, science fiction and fantasy book titles. You can see the results running at SF/F Name Generator.

Today, I’m going to run through a quick tutorial on how I wrote the Javascript that actually does the important part, selecting the random elements and putting them together into a name. If you’re not a confident coder, don’t worry – this is a very simple, entry-level web development problem, and you should be able to follow along easily enough. If you’ve got no idea what Javascript is, or what any of the words I’m using mean, W3Schools has some excellent resources for getting you up to speed.

Dealing with HTML

So, we’ve created an index.html to display our content, and a Javascript file (here called generator.js) to handle the logic. The first thing we have to do is include the script tag to let the browser know to load the file when it fetches the html. In HTML5, that’s as simple as putting this:

Читайте также:  Замена подстроки питон решение

js

into your header section. Once you’ve done that, you’re going to need to tell the browser when to run the function we’re going to write in our JS file. In this case, we want it to run our generator function once the rest of the page has loaded, so we add the following to our body tag:

We can also include a button to regenerate the name without reloading the whole page, which would look like this:

Great! All we need now is a div to hold our content, which our JS function will target when it inserts the generated name:

div

And we’re all done with the HTML. I’ll leave the rest of the structure and presentation up to you – in my example solution, I used the Twitter bootstrap library heavily to handle that, but that’s outside the scope of what we’re looking at today.

Random generation in JS

Right, now we know that our JS will load, and where it will go. But how do we get it to spit out our random name from a list of elements we want to stick together?

Well, what we need is a function – a block of code that all executes in order, and allows us to chain statements together and make more complicated logic operations than we could do with a single line. In order to use our function, we’re going to need to declare it. Open up generator.js, and enter this:

The function keyword tells the browser that whats comes after is going to be a function that it can call. Then comes the name, then a set of brackets where we would declare our inputs, if we had any, although in this case we don’t. Then comes a set of curly braces – these tell our browser that everything between them is part of the function, and should be run every time that function is called.

Our first objective is to set up two lists of words that we can smash together randomly to come up with names for our fictional titles. We do that using the var keyword to declare a new variable, then giving it a name, like so:

We also need to give our new variable a value – what set of things we’re talking about when we use the name ‘firstPart’. Javascript makes that very easy for us, as we can just use the equals operator to assign the value. However, since we’re putting in a list, this looks a little different:

var firstPart = [«The Coldness of», «The Journey to», «Altered by», «A Parallel of», . ];

Notice that we wrapped the list in square brackets, which tells the browser that this is a list of separate values that it can pick from. Also, we’ve ended the line with a semicolon – we have to do this to tell the browser that the code on this line is over, and it can look at it to decide what it means rather than carrying on.

We’re going to do that twice, to make two lists, one for the first part of the title, then one for the second part. Our JS file now looks like this:

// word lists
var firstPart = [«The Coldness of», «The Journey to», «Altered by», . ];
var secondPart = [«the Coming Order», «the Relationship of Command», «Evil Androids», . «];

The part with the two slashes is a comment, a note to ourselves about what the following lines mean that the browser will ignore when reading the file.

Okay, now we have our lists, how do we put them together? This is actually super simple – we just want to define a new variable called name, then stick together a random entry from the firstPart list, followed by a space, then a random entry from the secondPart list. That looks like:

var name = firstPart[Math.floor(Math.random() * firstPart.length)] + » » + secondPart[Math.floor(Math.random() * secondPart.length)];

Wait a moment, what does firstPart[Math.floor(Math.random() * firstPart.length)] mean? That’s the way we get our random element from the first list. We can call any part of a list by giving it an index number, starting from zero. So the first entry in our list, “The Coldness of”, is firstPart[0], the second is firstPart[1], and so on.

The code Math.floor(Math.random() * firstPart.length) picks a random number between zero and the total number of entries in our list. Math.random returns a number between zero and (almost) one, multiply that by your list length and you’ll get a random fraction of the list length to find. The Math.floor function takes that and finds the nearest integer number, without the fractional element, and so you get a whole number index to look at. Got it? No? Well, trust me that this will pick one element from your list, and investigate the details for yourself later.

Now, we have our random name. But how do we test that it’s working? Simple:

That will pop up a window with our generated name in it whenever we load the html page. Noice!

Dropping our name into a page element

Right now, our code looks like:

function generator() <
// word lists
var firstPart = [«The Coldness of», «The Journey to», «Altered by», «A Parallel of», . ];
var secondPart = [«the Coming Order», «the Relationship of Command», «Evil Androids», . ];

// generate name
var name = firstPart[Math.floor(Math.random() * firstPart.length)] + » » + secondPart[Math.floor(Math.random() * secondPart.length)];

That displays our name in a popup window, but what we really want is for our name to be displayed inside a div on the page – specifically a child of the placeholder element we created earlier. Let’s comment out that alert statement and work on getting it on the page instead.

To do that, we want to create a new element, give it a name, then put our text inside it. Then, we want to attach that element to the placeholder div. You can see the four lines that do so as follows:

var element = document.createElement(«div»);
element.setAttribute(«id», «name»);
element.appendChild(document.createTextNode(name));
document.getElementById(«placeholder»).appendChild(element);

And there we have it! Our name is displaying inside the placeholder div!

However, if you’ve been smart and implemented the button to create new names as alluded to above, you’ll notice that the new names are being added below our originals, and the list will soon scroll off the page. To avoid that, we’ll remove any existing name on the page by adding these lines of code before our ‘var element’ declaration:

if (document.getElementById(«name»)) document.getElementById(«placeholder»).removeChild(document.getElementById(«name»));
>

This smart little conditional will check to see if there is an existing page element with the id of ‘name’, then if so, will remove it from the placeholder div.

Everything altogether

Did you follow me? If not, don’t worry, here’s the whole generator.js file for you to check through at your own pace:

function generator() // word lists
var firstPart = [«The Coldness of», «The Journey to», «Altered by», «A Parallel of», «The Return of», . ];
var secondPart = [«the Coming Order», «the Relationship of Command», «Evil Androids», «Cybernetic Brain», . ];
// generate name
var name = firstPart[Math.floor(Math.random() * firstPart.length)] + » » + secondPart[Math.floor(Math.random() * secondPart.length)];
//alert(name);
// remove name div if existing
if (document.getElementById(«name»)) document.getElementById(«placeholder»).removeChild(document.getElementById(«name»));
>
// append to placeholder div
var element = document.createElement(«div»);
element.setAttribute(«id», «name»);
element.appendChild(document.createTextNode(name));
document.getElementById(«placeholder»).appendChild(element);
>

You can see my implementation on my RyanGoslingsBugle on GitHub, or check out some of the SeagalBot that I coded in Python that apply a lot of the same principles to random generation.

Источник

HTML Code for Random Name Generator

Helping individuals and teams improve their software development practices. Introducing testing, test automation, CI, CD, pair programming. That neighborhood.

Just a heads up that you can add highlighting to the code blocks if you’d like. Just change:

code block with no colors example

2 likes Like Comment button

1 like Like Comment button

For further actions, you may consider blocking this person and/or reporting abuse

Deploying Go & Redis For Free With Pebl!

Git Cheatsheet that will make you a master in Git

Why Choose Goodyear Tyres? Discover the Benefits at Brendale Goodyear

Laravel-Hands-On, a Learning resource for Laravel beginners

More from Zoya Khan

Once suspended, zoyakhanblogger will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, zoyakhanblogger will be able to comment and publish posts again.

Once unpublished, all posts by zoyakhanblogger will become hidden and only accessible to themselves.

If zoyakhanblogger is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Zoya Khan.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag zoyakhanblogger:

zoyakhanblogger consistently posts content that violates DEV Community’s code of conduct because it is harassing, offensive or spammy.

Unflagging zoyakhanblogger will restore default visibility to their posts.

DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey.

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 — 2023.

We’re a place where coders share, stay up-to-date and grow their careers.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

gitdagray/yt_random_name_generator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Build a Random Name Generator with Vanilla JavaScript, HTML, CSS

Description:

Build a Random Name Generator App Project with Vanilla JavaScript, HTML, and CSS. We’ll use many JavaScript, HTML, and CSS basics in this tutorial to create a Random Name Generator for YouTube Coding Channels.

If you have completed my 8 hour JavaScript course tutorial video, this is a great project for pulling some of those concepts together in one application.

DO NOT COPY FOR AN ASSIGNMENT — Avoid plagiargism and adhere to the spirit of this Academic Honesty Policy.

Источник

Оцените статью