≡ Menu

How To Code a Blog Title Generator in JavaScript, HTML, and CSS

Tyronne Ratcliff here. Ever wished you had a magical tool to instantly churn out catchy blog titles?

Well, with a bit of HTML, JavaScript, and CSS you can create your very own blog title generator!

The code below will:

  1. Create an HTML structure: It includes a heading, an input field for the keyword, a button to generate the title, and a paragraph to display the result.
  2. Style the elements: The CSS styles the elements for better readability and appearance.
  3. Implement the JavaScript logic:
    • When the “Generate Title” button is clicked, it gets the entered keyword.
    • It checks if the keyword is empty and displays an error message if it is.
    • It uses an array of title templates with placeholders.
    • It randomly selects a template and replaces the placeholder with the keyword.
    • It displays the generated title in the result paragraph.

<!DOCTYPE html>
<html>
<head>
    <title>Blog Title Generator</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>Blog Title Generator</h1>
        <input type="text" id="keyword" placeholder="Enter a keyword">
        <button onclick="generateTitle()">Generate Title</button>
        <p id="result"></p>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS:

.container {
    text-align: center;
    margin: 20px;
}

input, button {
    padding: 10px;
    font-size: 16px;
}

JavaScript:

function generateTitle() {
    const keyword = document.getElementById("keyword").value;
    const resultElement = document.getElementById("result");

    if (keyword.trim() === "") {
        resultElement.textContent = "Please enter a keyword.";
        return;
    }

    // Create an array of title templates
    const titleTemplates = [
        "The Ultimate Guide to {}",
        "How to {}",
        "5 Tips for {}",
        "The Future of {}",
        "A Beginner's Guide to {}",
        "The Surprising Truth About {}",
        "Why You Should {}",
        "The Benefits of {}",
        "The Best Ways to {}",
        "Is {} Worth It?"
    ];

    // Randomly select a template and replace the placeholder with the keyword
    const randomIndex = Math.floor(Math.random() * titleTemplates.length);
    const generatedTitle = titleTemplates[randomIndex].replace("{}", keyword);

    resultElement.textContent = generatedTitle;
}

You can customize it further by adding more title templates, implementing more complex logic, or integrating with APIs for more sophisticated title suggestions.

The last step is to deploy your code to a production environment where it can become accessible to users.

Two great places to deploy your code to are GitHUb and Vercel

Have any questions regarding the code in this tutorial? If so let me know
in the comments section below!

{ 0 comments… add one }

Leave a Comment

Previous post: