Complete the code to create a default action that logs a message when the element is clicked.
<script>
function logClick(node) {
function handleClick() {
console.log('Element clicked!');
}
node.addEventListener('click', [1]);
return {
destroy() {
node.removeEventListener('click', handleClick);
}
};
}
</script>
<button use:logClick>Click me</button>The handleClick function is the event listener that logs the message. It must be passed to addEventListener.
Complete the code to prevent the default form submission using a default action.
<script>
function preventSubmit(node) {
function handleSubmit(event) {
event.[1]();
alert('Form submission prevented');
}
node.addEventListener('submit', handleSubmit);
return {
destroy() {
node.removeEventListener('submit', handleSubmit);
}
};
}
</script>
<form use:preventSubmit>
<button type="submit">Submit</button>
</form>stopPropagation() which only stops event bubbling.The preventDefault() method stops the form from submitting and reloading the page.
Fix the error in the default action that should remove the event listener on destroy.
<script>
function highlight(node) {
function onMouseOver() {
node.style.backgroundColor = 'yellow';
}
node.addEventListener('mouseover', onMouseOver);
return {
destroy() {
node.[1]('mouseover', onMouseOver);
}
};
}
</script>
<p use:highlight>Hover over me</p>detachEvent.The correct method to remove an event listener is removeEventListener.
Fill both blanks to create a default action that toggles a CSS class on click and cleans up properly.
<script>
function toggleClass(node) {
function handleClick() {
node.classList.[1]('active');
}
node.addEventListener('click', handleClick);
return {
destroy() {
node.removeEventListener('click', [2]);
}
};
}
</script>
<div use:toggleClass>Click me to toggle class</div>add or remove instead of toggle.The toggle method adds or removes the class. The event listener to remove is handleClick.
Fill all three blanks to create a default action that updates the element's text on input and cleans up the event listener.
<script>
function updateText(node) {
function handleInput(event) {
node.value = event.target.[1];
}
node.addEventListener('[2]', handleInput);
return {
destroy() {
node.[3]('[2]', handleInput);
}
};
}
</script>
<input use:updateText placeholder="Type here" />text instead of value.change event instead of input.The input's current text is in event.target.value. The event is input. The listener is removed with removeEventListener.