Forum Moderators: open

Message Too Old, No Replies

More on preventDefault and stopPropagation

         

csdude55

9:35 pm on Nov 16, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It recently came to my attention that e.preventDefault() and e.stopPropagation() are automatically called if I use return false:
[api.jquery.com...]

Assuming that this isn't restricted to jQuery... I have a function that I half-borrowed and half-wrote a long time ago that looks like:

$('#comment')
.on('beforepaste paste', e => {
...
if (clp) {

// this is the function in question
kill(e);
//////

var type = 'plain';
if (clp.types.indexOf('text/html') !== -1) type = 'html';

a = editClip(clp.getData('text/' + type));
document.execCommand('insertHTML', false, a);

pasted = true;
}

return;
}
...
});

// here's the kill() function
function kill(e) {
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true;

if (e.preventDefault) e.preventDefault();
else e.returnValue = false;

return false;
}

If I'm understanding correctly, then can I simply replace the entire kill() function with return false;?

If so, is this different from replacing the ending return; with return false; and then removing kill() altogether?

robzilla

10:51 am on Nov 17, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Assuming that this isn't restricted to jQuery

It is. Here's a good write-up of the differences: [thisthat.dev...]

csdude55

7:10 pm on Nov 17, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Thanks for the link. From reading it, it seems like the significant difference is that return false would (obviously) have to come at the end, while preventDefault() could go anywhere. So in theory, if there's a runtime error in the script then using return false might allow something to run that you didn't want.