JavaScript Events and API Fetching Cheat Sheet
JavaScript Events:
1. Click Event:
element.addEventListener('click', function() {
// Code to be executed when element is clicked
});
2. Mouse Event:
element.addEventListener('mouseover', function() {
// Code to be executed when mouse hovers over the element
});
3. Keyboard Event:
element.addEventListener('keydown', function(event) {
// Code to be executed when a key is pressed
});
4. Change Event (for input fields):
element.addEventListener('change', function() {
// Code to be executed when input value changes
});
5. Submit Event (for forms):
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevents the form from submitting
// Code to be executed when the form is submitted
});
6. Focus Event:
element.addEventListener('focus', function() {
// Code to be executed when element receives focus
});
7. Blur Event:
element.addEventListener('blur', function() {
// Code to be executed when element loses focus
});
API Fetching:
1. Fetch API Basics:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Handle the fetched data
})
.catch(error => {
// Handle any errors
});
2. Sending POST Requests:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => {
// Handle the response data
})
.catch(error => {
// Handle any errors
});
3. Handling JSON Response:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
});
4. Using async/await with Fetch:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
fetchData();