Youtube Player with Javascript by CristianVillafane

YT Music Walkman
STEREO PLAYER
… Esperando Música …

Wikipedia API with JavaScript by Cristian Villafane

Wikipedia Search
Cargando artículo destacado…

Color Palette Builder API with JavaScript by Cristian Villafane

Color Palette Builder

Color Palette Builder

Generate schemes from any color and lock your favorites.

Live Preview

Project Phoenix: Weekly Report

System performance is stable. We’ve resolved 15 critical bugs this week. However, there’s a moderate security risk in the legacy auth module that needs immediate attention.

Copied!

MultiTools with JavaScript by Cristian Villafane

Multi Tools with Javascript by Cristian Villafane

Multi Tools with Javascript

by Cristian Villafane

Utilities

Currency Converter with Javascript

Loading…

Weather App with Javascript

Web Calculator with Javascript

0

English Dictionary with Javascript

Security

Password Generator with Javascript

Strength:
Time to crack:

Passphrase Generator with Javascript

Strength:
Time to crack:

Password Strength Checker

Strength:
Time to crack:

Explore this collection of powerful and intuitive web tools, all built with modern Javascript by Cristian Villafane. This project demonstrates practical applications of web development skills, from API integration to complex UI logic.

Currency Converter with JavaScript by Cristian Villafane

Currency Converter with JavaScript by Cristian Villafane

Currency Converter: A Javascript Tutorial by Cristian Villafane

A practical guide to building a financial tool by fetching real-time data from the FxRatesAPI.

In our interconnected world, knowing the real-time value of different currencies is essential for travel, business, and investment. A currency converter is a perfect project to practice asynchronous JavaScript and API interaction. This guide on Javascript by Cristian Villafane will walk you through creating a sleek, functional currency converter using the free and simple FxRatesAPI. We’ll focus on fetching data, updating the DOM dynamically, and providing a clean user experience.

Phase 1: The Structure – HTML for the Converter

The foundation of our application is the HTML structure. We need input fields for the user to enter the amount and select the currencies they wish to convert between. A clear and intuitive layout is key.

Designing the User Interface

We’ll use a main container for our tool. Inside, we’ll have a prominent display area for the result. The core of the interface will be the options section:

  • Amount: An <input type="number"> allows the user to enter the value they want to convert.
  • From & To Currencies: Two <select> dropdowns will hold the list of available currencies. We’ll populate these dynamically using JavaScript.
  • Swap Button: A simple button to quickly swap the “From” and “To” currencies is a great usability feature.

Phase 2: The Logic – Real-Time Conversion with JavaScript

This is where our application comes to life. The JavaScript will fetch the list of currencies, populate our dropdowns, and perform the conversion calculation whenever the user changes an input.

Fetching Data with the `fetch` API

On page load, we make a single call to the FxRatesAPI endpoint https://api.fxratesapi.com/latest. This returns all available exchange rates relative to a base currency (USD). We store these rates and use their keys to populate our currency selection dropdowns. This single-fetch approach is highly efficient.

Client-Side Conversion

Once we have all the rates, we don’t need to call the API again for every conversion. The logic is handled directly in the browser. To convert from currency A to currency B, we use the stored rates and a simple formula: (amount / rate of A) * rate of B. This makes the converter feel instantaneous. This approach is central in Javascript by Cristian Villafane for building fast, data-driven applications.

Currency Converter in Action

Below, you can try out the live currency converter. Enter an amount, select your currencies, and see the real-time result. This is the final product of applying the concepts from this tutorial.

Loading rates…

The Complete Converter Code

Here is the self-contained, performance-optimized code for the currency converter component. You can copy and paste this into your own project.

I hope you found this tutorial on Javascript by Cristian Villafane useful. Building a currency converter is an excellent way to practice working with external APIs and handling asynchronous operations in JavaScript. Use this project as a foundation to explore and add new features, such as historical data charts or a portfolio tracker. The only limit is your curiosity! 💹

Happy coding, Cristian Villafane

Dictionary App with JavaScript by Cristian Villafane

Dictionary App with JavaScript by Cristian Villafane

Dictionary App: A Javascript Tutorial by Cristian Villafane

A practical guide to fetching data from a free dictionary API, handling complex JSON, and building a dynamic, real-world application.

Creating a dictionary app is a step above a simple weather app, presenting a fantastic challenge for handling more complex data structures. It’s a perfect project for mastering HTML for structure, CSS for styling, and the asynchronous capabilities of JavaScript. In this guide on Javascript by Cristian Villafane, we will build a functional and modern dictionary app with a crucial autocomplete feature.

Phase 1: The Structure – HTML for the Interface

Every web application starts with a solid HTML structure. For our dictionary app, we need an input field for the word, a search button, a container for autocomplete suggestions, and a display area for the results, which will include the word, phonetics, audio, definitions, and more.

Designing the User Interface

We’ll create a main container with a search area and a display card. The UI will consist of:

  • Word Input: An <input type="text"> that allows the user to type a word. It will trigger a search for suggestions as the user types.
  • Search Button: A <button> integrated into the input field for a clean look.
  • Autocomplete List: A <div> that will be dynamically populated with word suggestions.
  • Display Card: A dedicated <div> to hold all the dictionary information.
<!-- Search Container -->
<div class="search-container">
  <input type="text" id="word-input" placeholder="Enter a word...">
  <button id="search-btn">
    <!-- SVG Search Icon -->
  </button>
  <div class="autocomplete-suggestions" id="autocomplete-list"></div>
</div>

<!-- Dictionary Display -->
<div class="dictionary-display" id="dictionary-display">
  <!-- Content injected by JS -->
</div>

Phase 2: The Logic – Two APIs for a Better Experience

This is where our application comes to life. To provide a great user experience with autocomplete, we will use two different APIs: one for word suggestions and another for the full dictionary data.

  • Autocomplete: We’ll use the Datamuse API (api.datamuse.com) for fast word suggestions as the user types. It’s free and requires no API key.
  • Definitions: Once a word is selected, we’ll use the Free Dictionary API (dictionaryapi.dev) to fetch detailed information.

Understanding the Dictionary API Response (JSON)

When we request a word from dictionaryapi.dev, it sends back a complex JSON object, often an array. This structure is more nested than a typical weather API response. A simplified version for the word “hello” looks like this:

[
  {
    "word": "hello",
    "phonetic": "/həˈloʊ/",
    "phonetics": [
      {
        "text": "/həˈloʊ/",
        "audio": "https://api.dictionaryapi.dev/media/pronunciations/en/hello-us.mp3"
      }
    ],
    "meanings": [
      {
        "partOfSpeech": "exclamation",
        "definitions": [
          {
            "definition": "Used as a greeting or to begin a phone conversation.",
            "example": "hello there, Katie!"
          }
        ],
        "synonyms": ["hi", "greetings"],
        "antonyms": ["goodbye"]
      }
    ]
  }
]

Notice the nested arrays for phonetics and meanings. To get the audio URL, we would access data[0].phonetics[0].audio. To get the first definition, we would use data[0].meanings[0].definitions[0].definition. Our JavaScript needs to navigate this structure carefully.

Phase 3: Interactivity and Displaying the Data

A great app feels responsive and fast. We’ll connect our logic to user events and ensure the experience is smooth.

Event Listeners and User Experience

We have multiple event listeners: one for the input event on the text field for autocomplete, another for the click event on the search button, and a listener for the `Enter` key. We also handle clicks on the suggestion items. A default word is loaded on page open to provide an immediate example.

Dictionary App in Action

Below, you can try out the live dictionary app. Enter a word and see how the autocomplete suggests options. Select one to view its full definition, pronunciation, and more. This is the final result of applying the concepts from this tutorial.

The Complete Dictionary App Code

Here is the self-contained, performance-optimized code for the dictionary app. You can copy and paste this into your own project. It uses free APIs that don’t require keys.

<!-- HTML Structure -->
<div class="dictionary-container">
    <div class="search-container">
        <input type="text" id="word-input" placeholder="Enter a word..." aria-label="Word">
        <button id="search-btn" aria-label="Search">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>
        </button>
        <div class="autocomplete-suggestions" id="autocomplete-list"></div>
    </div>
    <div id="dictionary-display" class="dictionary-display">
        <!-- Dictionary data will be dynamically inserted here -->
    </div>
</div>

<!-- JavaScript Logic -->
<script>
document.addEventListener('DOMContentLoaded', () => {
    const container = document.querySelector('.dictionary-container:not(:has(#word-input-live))');
    if (!container) return;

    const wordInput = container.querySelector('#word-input');
    const searchBtn = container.querySelector('#search-btn');
    const dictionaryDisplay = container.querySelector('#dictionary-display');
    const autocompleteList = container.querySelector('#autocomplete-list');

    const fetchWordData = async (word) => {
        dictionaryDisplay.innerHTML = '<p style="text-align:center; padding: 2rem;">Loading...</p>';
        const apiUrl = `https://api.dictionaryapi.dev/api/v2/entries/en/${word}`;

        try {
            const response = await fetch(apiUrl);
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.title || 'Word not found. Please try again.');
            }
            const data = await response.json();
            displayWordData(data, dictionaryDisplay);
        } catch (error) {
            displayError(error.message, dictionaryDisplay);
        }
    };

    const fetchAutocomplete = async (query, listElement) => {
        if (query.length < 2) {
            listElement.innerHTML = '';
            listElement.style.display = 'none';
            return;
        }
        const apiUrl = `https://api.datamuse.com/sug?s=${query}`;
        try {
            const response = await fetch(apiUrl);
            if (!response.ok) return;
            const suggestions = await response.json();
            displayAutocomplete(suggestions, listElement);
        } catch (error) {
            console.error('Autocomplete error:', error);
            listElement.style.display = 'none';
        }
    };
    
    const displayWordData = (data, displayElement) => {
        const entry = data[0];
        const phoneticInfo = entry.phonetics.find(p => p.audio) || entry.phonetics[0];
        
        let meaningsHtml = entry.meanings.map(meaning => `
            <div class="meaning-block">
                <h3 class="part-of-speech">${meaning.partOfSpeech}</h3>
                <ol class="definition-list">
                    ${meaning.definitions.map(def => `
                        <li class="definition-item">
                            ${def.definition}
                            ${def.example ? `<p class="definition-example">e.g., "${def.example}"</p>` : ''}
                        </li>
                    `).join('')}
                </ol>
                ${meaning.synonyms && meaning.synonyms.length > 0 ? `
                    <div class="synonyms-antonyms">
                        <h4>Synonyms:</h4>
                        ${meaning.synonyms.map(s => `<span>${s}</span>`).join('')}
                    </div>
                ` : ''}
                ${meaning.antonyms && meaning.antonyms.length > 0 ? `
                    <div class="synonyms-antonyms">
                        <h4>Antonyms:</h4>
                        ${meaning.antonyms.map(a => `<span>${a}</span>`).join('')}
                    </div>
                ` : ''}
            </div>
        `).join('');

        displayElement.innerHTML = `
            <div class="word-header">
                <div>
                    <h2 class="word-title">${entry.word}</h2>
                    <p class="phonetic">${phoneticInfo ? phoneticInfo.text : 'N/A'}</p>
                </div>
                ${phoneticInfo && phoneticInfo.audio ? `
                    <button class="audio-btn" onclick="this.querySelector('audio').play()" aria-label="Play audio">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
                        <audio src="${phoneticInfo.audio}"></audio>
                    </button>
                ` : ''}
            </div>
            ${meaningsHtml}
        `;
    };

    const displayAutocomplete = (suggestions, listElement) => {
        if (!suggestions || suggestions.length === 0) {
            listElement.style.display = 'none';
            return;
        }
        listElement.innerHTML = suggestions.map(s => 
            `<div class="suggestion-item" data-word="${s.word}">${s.word}</div>`
        ).join('');
        listElement.style.display = 'block';
    };

    const displayError = (message, displayElement) => {
        displayElement.innerHTML = `<p id="error-message">Error: ${message}</p>`;
    };
    
    const performSearch = (word) => {
        if (word) {
            fetchWordData(word);
            wordInput.value = word;
            autocompleteList.style.display = 'none';
        }
    };

    searchBtn.addEventListener('click', () => performSearch(wordInput.value));
    wordInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') performSearch(wordInput.value);
    });
    wordInput.addEventListener('input', () => fetchAutocomplete(wordInput.value, autocompleteList));

    autocompleteList.addEventListener('click', (e) => {
        if (e.target.classList.contains('suggestion-item')) {
            const word = e.target.dataset.word;
            performSearch(word);
        }
    });
    
    document.addEventListener('click', (e) => {
        if (!e.target.closest('.search-container')) {
            autocompleteList.style.display = 'none';
        }
    });

    fetchWordData('keyboard');
});
</script>

I hope you found this tutorial on Javascript by Cristian Villafane useful. Building a dictionary app is an excellent way to practice handling more complex API responses and creating a more sophisticated UI. Use this project as a starting point to explore and add new features, like saving favorite words or displaying usage source URLs. The only limit is your curiosity! 📚

Happy coding, Cristian Villafane

Weather App with JavaScript by Cristian Villafane

Weather App with JavaScript by Cristian Villafane

Weather App: A Javascript Tutorial by Cristian Villafane

A practical guide to connecting to a live API, handling data, and building a dynamic, real-world application.

Connecting your application to data from the real world is a fundamental skill for any web developer. A weather app is the perfect project for this, teaching you how to communicate with external services and display live information. This project is a fantastic exercise to master HTML, CSS, and the asynchronous capabilities of JavaScript. In this guide on Javascript by Cristian Villafane, we will build a functional and beautiful weather app from the ground up.

Phase 1: The Structure – HTML for the Interface

Every web application starts with a solid HTML structure. For our weather app, the HTML will define the user input area and the display for the weather data. We’ll need an input field for the city, a button to initiate the search, and a card to show the results. Now, we’ll also add a container for autocomplete suggestions.

Designing the User Interface

We begin with a main container. Inside, we’ll create a search area with an input and a button, a container for autocomplete suggestions, and a display card for the results. The user interface will consist of:

  • City Input: An <input type="text"> allows the user to type the name of a city. It will now trigger a search for city suggestions as the user types.
  • Search Button: A <button> with a search icon is now integrated into the input field for a cleaner look.
  • Autocomplete List: A <div> that will be dynamically populated with city suggestions from the API.
  • Display Card: A dedicated <div> will hold all the weather information: city name, local time, temperature, icon, condition, and other details like humidity, feels like temperature, and wind speed.
<!-- Search Container -->
<div class="search-container">
  <input type="text" id="city-input" placeholder="Enter city name...">
  <button id="search-btn">
    <!-- SVG Search Icon -->
  </button>
  <div class="autocomplete-suggestions" id="autocomplete-list"></div>
</div>

<!-- Weather Display -->
<div class="weather-display" id="weather-display">
  <!-- Content injected by JS -->
</div>

Phase 2: The Logic – Fetching and Displaying API Data

This is where our application comes to life. The JavaScript will listen for user input, make requests to the WeatherAPI, parse the response, and update the HTML to show the current weather conditions.

Understanding the API Response (JSON)

When we make a successful request to the API, it sends back a large block of text in JSON (JavaScript Object Notation) format. Our script then parses this text into a JavaScript object that we can easily work with. A simplified version of this object looks like this:

{
  "location": {
    "name": "London",
    "country": "United Kingdom",
    "localtime": "2023-10-27 13:00"
  },
  "current": {
    "temp_c": 12.0,
    "feelslike_c": 11.2,
    "humidity": 75,
    "wind_kph": 15.1,
    "uv": 3.0,
    "condition": {
      "text": "Partly cloudy",
      "icon": "//cdn.weatherapi.com/weather/64x64/day/116.png"
    }
  }
}

To access a piece of data, we use dot notation. For example, to get the temperature in Celsius, we would access data.current.temp_c, where data is the variable holding our parsed JSON object. To get the condition text (“Partly cloudy”), we need to go deeper: data.current.condition.text.

Customizing the Displayed Information

The best part of using an API is that you can choose exactly what to show. Let’s say you want to add the UV Index to our display.

  1. Find the data: Looking at the JSON above, the UV index is at current.uv.
  2. Add an HTML element: In our `displayWeather` function, we add a new `div` inside the `weather-details` section to hold this information.
    <div class="detail-item">
      <div class="detail-label">UV Index</div>
      <div class="detail-value">${current.uv}</div>
    </div>
  3. That’s it! By adding that snippet to our template literal in the JavaScript, the UV index will now appear on the card. The process is the same for any other data point you want to add. To remove an item, simply delete its corresponding `div` from the template.

Customizing the API Request (Language)

WeatherAPI allows us to customize the request using URL parameters. One of the most useful is `lang`, which changes the language of certain text fields in the response, like the weather condition.

In our code, the API URL is constructed like this:

const apiUrl = `https://api.weatherapi.com/v1/forecast.json?key=${apiKey}&q=${city}&lang=en`;

The part &lang=en tells the API to return the condition text in English (e.g., “Partly cloudy”). If you wanted the text in Spanish, you would simply change it to &lang=es. If you wanted French, you would use &lang=fr. This makes it easy to internationalize your application. The labels on your card (like “Humidity” or “Wind”) are hardcoded in our HTML template, so you would need to change those manually to match the language you choose.

Phase 3: Interactivity and Performance Optimization

A great app feels responsive and fast. We’ll connect our logic to user events and ensure the experience is smooth by using the same performance optimizations from the original template, such as non-blocking font loading.

Event Listeners and User Experience

We now have multiple event listeners: one for the `input` event on the text field to handle autocomplete, another for the `click` event on the search button, and a listener for the `Enter` key. We also handle clicks on the suggestion items to trigger a weather search. A default city is still loaded on page open to provide an immediate example.

Weather App in Action

Below, you can try out the live weather app. Enter a city name and see the new design, the added information, and the autocomplete functionality for yourself. This is the final result of applying the concepts from this tutorial.

The Complete Weather App Code

Here is the self-contained, performance-optimized code for the weather app component. You can copy and paste this into your own project. Remember to replace 'YOUR_API_KEY' with your actual key from WeatherAPI.com.

<!-- HTML Structure -->
<div class="weather-container">
    <div class="search-container">
        <input type="text" id="city-input" placeholder="Enter a city..." aria-label="City Name">
        <button id="search-btn" aria-label="Search">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>
        </button>
        <div class="autocomplete-suggestions" id="autocomplete-list"></div>
    </div>
    <div id="weather-display" class="weather-display">
        <!-- Weather data will be dynamically inserted here -->
    </div>
</div>

<!-- JavaScript Logic -->
<script>
// NOTE: This script block is for demonstration purposes only in this complete code view.
// In a real implementation, you would have a single script block at the end of your page
// to handle all interactivity, as shown in the final script of this document.
document.addEventListener('DOMContentLoaded', () => {
    const apiKey = 'YOUR_API_KEY'; // Replace with your key
    const cityInput = document.getElementById('city-input');
    const searchBtn = document.getElementById('search-btn');
    const weatherDisplay = document.getElementById('weather-display');
    const autocompleteList = document.getElementById('autocomplete-list');

    // ... (rest of the functions: fetchWeather, displayWeather, etc.)
});
</script>

I hope you found this tutorial on Javascript by Cristian Villafane useful. Building a weather app not only reinforces your knowledge of asynchronous JavaScript, but it also provides a practical foundation for working with any third-party API. Use this project as a starting point to explore and add new features, like a multi-day forecast or geolocation. The only limit is your curiosity! 🌦️

Happy coding, Cristian Villafane