Skip to main content

Task 17: Predict Gender Using a Name with JavaScript & API | Beginner Web Project

Start with Affirmation​

  • I declare that I am focused, creative, and capable of solving any challenge that comes my way.

  • I declare that every task I complete brings me closer to mastery and success.

  • I declare that my mind is sharp, my heart is committed, and my energy is aligned with growth.

  • I declare that learning comes easily to me, and I enjoy discovering new ways to create and innovate.

  • I declare that I am becoming more confident with every step I take in this journey.

  • I declare that what I build today has the power to impact the future.

  • I declare that I am consistent, disciplined, and driven by purpose.

  • I declare that I finish what I start with excellence and joy.

  • I declare that today is a gift, and I make it count with every line of code and every creative idea.

πŸ’ͺ Repeat daily, feel the power, and watch your success unfold!


πŸ”Ή If you don’t understand the task, watch the video above for the answer.


Task​


** Step 1: HTML​

<h1>πŸ§‘ Predict Gender</h1>
<input type="text" id="nameInput" placeholder="Enter your name" />
<button id="predictGenderBtn">Guess My Gender</button>
<p id="genderResult">Your predicted gender will appear here!</p>

<!-- Axios CDN -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<!-- Link to JS file -->
<script src="script.js"></script>

Step 2: JS​

const genderBtn = document.getElementById("predictGenderBtn");
const nameInput = document.getElementById("nameInput");
const genderResult = document.getElementById("genderResult");

genderBtn.addEventListener("click", () => {
const name = nameInput.value.trim();

if (name === "") {
genderResult.textContent = "Please enter a name.";
return;
}

axios.get(`https://api.genderize.io?name=${encodeURIComponent(name)}`)
.then(response => {
const predictedGender = response.data.gender;
if (predictedGender !== null) {
genderResult.textContent = `πŸ§‘ Based on the name "${name}", the predicted gender is ${predictedGender}.`;
} else {
genderResult.textContent = `πŸ€” Sorry, we couldn't predict the gender for the name "${name}".`;
}
})
.catch(error => {
console.error("Error fetching gender:", error);
genderResult.textContent = "Oops! Something went wrong. Try again.";
});
});