const log = console.log;
const child = document.getElementById('child');
const parent = document.getElementById('parent');
parent.addEventListener('newColor', function(e) {
e.preventDefault()
log('parent')
this.style.color = e.detail.textColor;
})
child.addEventListener('newColor', function(e) {
log('child')
this.style.color = e.detail.textColor;
this.style.backgroundColor = e.detail.bgrColor;
})
function changeColor() {
const myEvent = new CustomEvent('newColor', {
detail: {
textColor: 'red',
bgrColor: 'blue',
},
cancelable: true,
bubbles: true
})
child.dispatchEvent(myEvent);
}
changeColor()
<p id="parent">this is the parent<span id="child"> THIS IS THE CHILD ELEMENT </span></p>
Since event.preventDefault()
only prevent the default browser action, how can a custom Event be 'canceled' then?
For example, in here:
$("#but").click(function (ev) {
ev.preventDefault()
alert('child button clicked');
})
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<button id="but">button</button>
the preventDefault()
only prevents the default action, which would be to submit a form, not the execution of the rest of the function statements.
So, what is the point of having 'cancellable' property when you can't actually cancel a event with preventDefault()
?