Javascript code examples most web development solution
1. JavaScript AJAX Request with Fetch API:
Example: Fetching Weather Data from an API
javascript Copy code
Explanation: In this example, we use the Fetch API to make an asynchronous request to the OpenWeatherMap API to retrieve weather data for London. The URL contains the location and an API key (replace 'your-api-key' with an actual API key). Once the data is received, we extract the temperature in Kelvin from the response and convert it to Celsius. The result is logged to the console.
Explanation: In this example, we create a to-do list feature. We have an unordered list (ul) with the ID 'todoList,' an input field with the ID 'todoInput,' and a button with the ID 'addButton.' When the button is clicked, a new list item (li) is dynamically created, and its content is set to the value of the input field. The new item is then appended to the to-do list, and the input field.
const weatherAPI = 'https://api.openweathermap.org/data/2.5/weather?q=London&appid=your-api-key'; fetch(weatherAPI) .then(response => response.json()) .then(data => { const temperature = data.main.temp - 273.15; // Convert from Kelvin to Celsius console.log(`Current temperature in London: ${temperature.toFixed(2)}°C`); }) .catch(error => { console.error('Error:', error); });
2. JavaScript Promises:
Example: Loading Images with a Promise
javascript Copy code
Explanation: Here, we create a function loadImage that returns a Promise. It loads an image from a given URL and resolves when the image is successfully loaded or rejects if there's an error. After the image is loaded, it is appended to the document's body. If there's an error, it's caught and logged.
function loadImage(url) { return new Promise((resolve, reject) => { const image = new Image(); image.src = url; image.onload = () => resolve(image); image.onerror = (error) => reject(error); }); } loadImage('image.jpg') .then(image => { document.body.appendChild(image); }) .catch(error => { console.error('Error loading image:', error); });
3.Working with Arrays:
Example: Filtering Even Numbers from an Array
javascript Copy code
Explanation: In this example, we have an array of numbers, and we use the filter method to create a new array called evenNumbers. This new array contains only the even numbers from the original array, which is determined by checking if the remainder of each number divided by 2 is equal to 0. Finally, we log the even numbers to the console.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log('Even numbers:', evenNumbers);
4.JavaScriptt Event Handling:
Example:
Handling a Submit Button in a Contact Form
javascriptCopy code
Explanation: In this code, we target an HTML element with the ID 'submitBtn,' which is presumably a submit button in a contact form. We add a click event listener to it. When the button is clicked, the default form submission is prevented using event.preventDefault(), and a confirmation message is displayed in an element with the ID 'confirmationMessage.'
const submitButton = document.getElementById('submitBtn'); const message = document.getElementById('confirmationMessage'); submitButton.addEventListener('click', function(event) { event.preventDefault(); // Prevent the form from submitting message.textContent = 'Form submitted successfully!'; });
5.JavaScript Form Validation:
Example: Validating Email Input in a Registration Form
javascriptCopy code
Explanation: This code is designed to validate an email input field in a registration form. It adds a submit event listener to the form. If the email is not valid (as determined by the isValidEmail function and a regular expression test), the form submission is prevented, and an error message is displayed.
const registrationForm = document.getElementById('registrationForm'); const emailInput = document.getElementById('email'); const errorText = document.getElementById('errorText'); registrationForm.addEventListener('submit', function(event) { if (!isValidEmail(emailInput.value)) { event.preventDefault(); errorText.textContent = 'Invalid email address.'; } }); function isValidEmail(email) { // Perform email validation here return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); }
6.JavaScriptt DOM Manipulation:
Example: Creating a To-Do List Item Dynamically
javascriptCopy code
const todoList = document.getElementById('todoList'); const addButton = document.getElementById('addButton'); const inputField = document.getElementById('todoInput'); addButton.addEventListener('click', function() { const newItem = document.createElement('li'); newItem.textContent = inputField.value; todoList.appendChild(newItem); inputField.value = ''; // Clear the input field });