Build a Custom Slug Generator using HTML, CSS, and JavaScript

Faraz

By Faraz - Last Updated:

Learn how to create a custom slug generator with HTML, CSS, and JavaScript. Our step-by-step guide will show you how to build and test your own slug generator.


build a custom slug generator using html, css, and javascript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

A slug generator is a tool that creates a simplified version of a URL string, often to make it more human-readable and SEO-friendly. A slug is the part of a URL that identifies a specific page or post on a website. It is typically located after the domain name and is used to identify the content of the page or post. For example, in the URL www.example.com/this-is-a-slug, this-is-a-slug would be the slug.

Slug generators can be used to automatically create slugs from the title of a page or post, or they can be used to manually customize the slug to a specific format. Slug generators can be implemented in a variety of programming languages, such as HTML, CSS, and JavaScript.

A Slug Generator is a tool that automatically generates slugs for webpages or blog posts. This is useful for several reasons:

  1. Slugs are important for SEO (search engine optimization), as they help search engines understand the content of a webpage.
  2. Slugs can make URLs more user-friendly, as they can be customized to be shorter and easier to remember.
  3. Slugs can prevent naming conflicts, as they ensure that every page or post has a unique identifier.

Benefits of using a Custom Slug Generator

While many online tools can generate slugs, building your own Custom Slug Generator has several benefits:

  • Personalization: A Custom Slug Generator allows you to create slugs that reflect your brand or website's personality.
  • Aesthetics: A Custom Slug Generator allows you to create slugs that are visually appealing and easy to remember.
  • Flexibility: A Custom Slug Generator allows you to create slugs that meet your specific needs and requirements.
  • Control: A Custom Slug Generator allows you to have complete control over the slug creation process.

You can use codewithfaraz's text to slug generator tool that allows you to use a slug generator tool online.

Let's start making an amazing responsive slug generator tool Using HTML, CSS, and JavaScript step by step.

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include creating a form element to input the title of the page or post, and a button to trigger the slug generation. Below is a detailed explanation of each section:

1. Document Declaration & Head Section

<!DOCTYPE html>
<html lang="en">
  • Declares the document as HTML5.
  • Specifies that the language is English (lang="en").
<head>
  <title>Custom Slug Generator</title>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width" />
  <link rel="stylesheet" href="styles.css" />
</head>
  • <title>: Sets the page title as "Custom Slug Generator".
  • <meta charset="UTF-8">: Ensures proper text encoding for various characters.
  • <meta name="viewport" content="width=device-width">: Makes the page responsive.
  • <link rel="stylesheet" href="styles.css">: Links an external CSS file (styles.css) for styling.

2. Body Section

Header

<header>
  <h1>Slug Generator</h1>
</header>
  • Displays the main heading (<h1>Slug Generator)**.
  • <header> is a semantic tag used for page headings.

3. Main Content (<main>)

<main>
  <form id="generator">
    <label for="title">Generate a slug from post title:</label>
    <input type="text" name="title" id="title" placeholder="The title needs slug" onfocus="this.value=''">
    <button class="primary-button" type="submit">Generate</button>
  </form>
  • <form>:
    • ID: generator (used for JavaScript manipulation).
    • Contains an input field for the user to enter a title.
  • <label>: Describes the input field.
  • <input>:
    • type="text": Text input field.
    • name="title" and id="title": Used for JavaScript to fetch the input.
    • placeholder="The title needs slug": Displays a hint inside the input.
    • onfocus="this.value=''**: Clears input when clicked.
  • <button>:
    • class="primary-button": Used for styling.
    • type="submit": Submits the form to generate the slug.

4. Displaying the Generated Slug

<div id="result">
  <input type="text" >
  <button class="default-button" id="copy" type="button">Copy</button>
</div>
  • <div id="result">: Holds the generated slug.
  • <input type="text">: Displays the slug (user-generated text).
  • <button>:
    • class="default-button": Styling for the copy button.
    • id="copy": Used in JavaScript to copy the slug.
    • type="button": Prevents page refresh when clicked.

5. Linking JavaScript

<script src="script.js"></script>
  • Links script.js (JavaScript file) to handle slug generation & copying.

After creating the files just paste the following codes into your file. Remember that you must save a file with the .html extension.

Step 2 (CSS Code):

Next, we will create our CSS file. In this file, we will use some basic CSS rules. Below is a detailed breakdown of each section:

1. Root Variables (Global Colors)

html {
  --clr-white: #ffffff;
  --clr-primary: hsl(259deg 64% 59%);
}
  • Defines CSS variables (--clr-white, --clr-primary) for consistent color usage.
  • --clr-primary is an HSL color used for buttons and input focus.

2. Universal Styles (Reset and Box Sizing)

*, *::before, *::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
  • Resets margins and paddings for all elements.
  • box-sizing: border-box; ensures that padding and border are included in element width.

3. Body Styling

body {
  font-family: sans-serif;
  font-size: 18px;
  background-color: #fafafa;
  color: #333333;
  padding: 2rem;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: stretch;
}
  • Uses sans-serif font.
  • Background color: #fafafa (light gray).
  • Text color: #333333 (dark gray).
  • Adds padding (2rem).
  • Uses flexbox to center content vertically on the screen (min-height: 100vh).

4. Spacing Between Elements

body > * + * {
  margin-top: 1em;
}
  • Adds 1em spacing between sibling elements.

5. Header & Main Styling

header, main {
  max-width: 600px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
}
  • Centers content horizontally (margin-left: auto; margin-right: auto;).
  • Limits the width to 600px.

6. Form (#generator) Styling

#generator {
  --paddingX: calc(.75em - 1px);
  --paddingY: calc(.5em - 1px);
  --borderR: 0.375em;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 0.75rem;
}
  • Uses CSS variables for padding and border-radius.
  • Flexbox layout for vertical alignment.
  • gap: 0.75rem; adds spacing between form elements.

7. Input Field Styling

input[type="text"] {
  font-size: 1em;
  background-color: var(--clr-white);
  border: 1px solid #dbdbdb;
  border-radius: var(--borderR);
  padding: var(--paddingY) var(--paddingX);
  box-shadow: inset 0 0.0625em 0.125em rgb(10 10 10 / 5%);
}
  • White background (var(--clr-white)).
  • Light gray border (#dbdbdb).
  • Rounded corners (border-radius: var(--borderR)).
  • Box shadow for inner depth effect.

Input Field Focus Effect

input[type="text"]:focus {
  outline: none;
  border-color: var(--clr-primary);
  box-shadow: 0 0 0 0.125em rgb(72 95 199 / 25%);
}
  • Removes default outline.
  • Changes border color to primary color (var(--clr-primary)) on focus.
  • Adds a soft blue glow effect (box-shadow).

8. Button Styling

button {
  text-align: center;
  font: inherit;
  color: var(--color);
  background: var(--bgColor);
  border: 1px solid var(--borderColor);
  border-radius: var(--borderR);
  padding: var(--paddingY) var(--paddingX);
  margin: 0;
  display: block;
  cursor: pointer;
}
  • Uses CSS variables for colors (--color, --bgColor, --borderColor).
  • Rounded corners (border-radius: var(--borderR)).
  • Clickable cursor (cursor: pointer;).

Focus Effect

button:focus {
  outline-offset: 2px;
}
  • Moves the focus outline 2px outside the button.

9. Button Variants

Primary Button (For "Generate" Button)

.primary-button {
  --color: var(--clr-white);
  --bgColor: var(--clr-primary);
  --borderColor: var(--clr-primary);
}
  • White text (--color).
  • Primary background color (--bgColor).
  • Same color border (--borderColor).

Default Button (For "Copy" Button)

.default-button {
  --color: hsl(217deg 23% 27%);
  --bgColor: var(--clr-white);
  --borderColor: hsl(216deg 16% 84%);
}
  • Dark blue text (hsl(217deg 23% 27%)).
  • White background (var(--clr-white)).
  • Light gray border.

10. Slug Output Container (#result)

#result {
  visibility: hidden;
  --paddingX: 6px;
  --paddingY: 2px;
  --borderR: 0.375em;
  background-color: hsl(220deg 17% 93%);
  color: #da1039;
  padding: calc(var(--paddingY) * 5) calc(var(--paddingX) * 2);
  margin-top: 1.5em;
  display: flex;
  align-items: flex-start;
  gap: 2rem;
}
  • Hidden initially (visibility: hidden) until slug is generated.
  • Light gray background (hsl(220deg 17% 93%)).
  • Text color (#da1039) for error or alert styling.
  • Flexbox layout for proper alignment.

11. Slug Output Input Styling

#result input {
  font-size: 1em;
  background: transparent;
  border: none;
  height: auto;
  resize: none;
  display: block;
  flex: 1;
}
  • Transparent background (blends with container).
  • No border.
  • Resizable disabled (resize: none;).
  • Takes up full width (flex: 1;).

This can help to make the page more visually appealing and easier to use. Create a CSS file with the name styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

html {
  --clr-white: #ffffff;
  --clr-primary: hsl(259deg 64% 59%);
}

*, *::before, *::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
  font-size: 18px;
  background-color: #fafafa;
  color: #333333;
  padding: 2rem;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: stretch;
}

body > * + * {
  margin-top: 1em;
}

header, main {
  max-width: 600px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
}

#generator {
  --paddingX: calc(.75em - 1px);
  --paddingY: calc(.5em - 1px);
  --borderR: 0.375em;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: 0.75rem;
}

input[type="text"] {
  font-size: 1em;
  background-color: var(--clr-white);
  border: 1px solid #dbdbdb;
  border-radius: var(--borderR);
  padding: var(--paddingY) var(--paddingX);
  box-shadow: inset 0 0.0625em 0.125em rgb(10 10 10 / 5%);
}

input[type="text"]:focus {
  outline: none;
  border-color: var(--clr-primary);
  box-shadow: 0 0 0 0.125em rgb(72 95 199 / 25%);
}

button {
  text-align: center;
  font: inherit;
  color: var(--color);
  background: var(--bgColor);
  border: 1px solid var(--borderColor);
  border-radius: var(--borderR);
  padding: var(--paddingY) var(--paddingX);
  margin: 0;
  display: block;
  cursor: pointer;
}

button:focus {
  outline-offset: 2px;
}

.primary-button {
  --color: var(--clr-white);
  --bgColor: var(--clr-primary);
  --borderColor: var(--clr-primary);
}

.default-button {
  --color: hsl(217deg 23% 27%);
  --bgColor: var(--clr-white);
  --borderColor: hsl(216deg 16% 84%);
}

#result {
  visibility: hidden;
  --paddingX: 6px;
  --paddingY: 2px;
  --borderR: 0.375em;
  background-color: hsl(220deg 17% 93%);
  color: #da1039;
  padding: calc(var(--paddingY) * 5) calc(var(--paddingX) * 2);
  margin-top: 1.5em;
  display: flex;
  align-items: flex-start;
  gap: 2rem;
}

#result input {
  font-size: 1em;
  background: transparent;
  border: none;
  height: auto;
  resize: none;
  display: block;
  flex: 1;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function that will take the inputted title and generate a slug from it. This function will involve manipulating the inputted text to remove spaces and special characters and then formatting it in a way that is suitable for use as a URL slug.

Bind the slug generation function to the form submission event, so that it is triggered when the user clicks the button to generate the slug.

Test your slug generator to make sure it is working correctly. This may involve inputting different titles and verifying that the generated slugs are correct.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with .js extension.

(Optional) If you want you can add additional features to your slug generator, such as the ability to edit the generated slug manually or to preview the full URL with the slug included.

const generator = document.getElementById("generator");
const result = document.querySelector("#result input");
const copy = document.getElementById("copy");
const showDiv = document.getElementById("result");

generator.addEventListener("submit", function (e) {
  e.preventDefault();

  const title = e.target.title.value;
  const slug = title.toLowerCase().split(" ").join("-").replace(/[:.,?!]/gi, "");

  if (result) {
    result.value = slug;
    e.target.title.value = "";
    showDiv.style.visibility = "visible";
  } else {
    console.error("Sth wrong...");
  }
});

function copy2clipboard() {
  let custom_code = result.select();
    document.execCommand('copy'); 
}

copy.addEventListener("click", copy2clipboard);

Final Output:

build a custom slug generator using html, css, and javascript.gif

Conclusion:

In this tutorial, we have shown you how to build a Custom Slug Generator using HTML, CSS, and JavaScript. We started by discussing what a Slug Generator is and the benefits of using a Custom Slug Generator. Then, we provided a step-by-step guide to building a Custom Slug Generator, including setting up the HTML structure, designing the CSS layout, writing the JavaScript code, and testing and optimizing the generator.

Along the way, we also provided best practices for creating a Slug Generator, such as using user-friendly and descriptive slugs, handling edge cases, and ensuring the generator is accessible and responsive.

By building your own Custom Slug Generator, you can create slugs that are personalized, aesthetically pleasing, and meet your specific needs and requirements. We hope that this tutorial has been helpful and that you are now equipped to create your own Custom Slug Generator.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺