Return exits the function with that return value. your preventDefault
never gets reached.
console.log(e.target); // Log stuff
return false; // Exit function
e.preventDefault(); // unreachable
Also in your second codeblock you never defined e. So even if it would reach the e.preventDefault();
line it would fail with Uncaught ReferenceError: e is not defined
Edit
You need to check if the propagation has stopped in
var content = $('#frut');
$(function () {
// kabhoom = $.Event('click');
$('a').on( 'kabhoom' , function(e){
// Are we good to go? Or has it stopped?
if(!e.isPropagationStopped()) {
content.append("Target = "+e.target+"<BR/>Cancelling Events<br/>");
e.preventDefault();
e.stopPropagation();
e.cancelBubble =true;
return false;
}
})
});
$('a').click(function(e){
content.append('Normal click event<BR/>');
$(this).trigger('kabhoom');
e.preventDefault();
return false;
})
// wrapping in ready because otherwise the order is messed up that the event listeners are registered.
$(document).ready(function(){
$('a').on( 'kabhoom' , function(e){
// Are we good to go? Or has it stopped?
if(!e.isPropagationStopped()) {
content.append('Should not appear<BR/>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="frut">
</div>
<a href="https://www.google.com">KHaboom?</a>
Edit 2
Your problem comes down to this:
Your khaboom event has NO way to stop the click propagation. The khaboom is triggered as a separate process by the trigger command.
It gets it's own event stream, but has no relation to the click event that triggered it. So it can cancel itself, it can prevent whatever you define should or should not happen, but it cannot touch the click event because there is no reference to it, nor does the click event wait for it.
You can see it as two streams diverging but never touching again. Where one stream ends in the ocean, the other stream runs dead in the mountains(the ocean being navigate wherever). Whilst the other stream in the mountains just does it's thing with the mountains(whatever you decide should happen on its khaboom event).
Visualization:
CLICK
||
||
\/
EVENT
||
||
\/
jQuery.on() call all clicks
||
||
\/
click found trigger khaboom=========== <-- absolute seperation. no more link between two threads.
|| ||
|| ||
\/ \/
no more click events EVENT
|| ||
|| ||
\/ \/
has preventDefault been called? jQuery.on() call all khaboom
|| ||
|| ||
\/ \/
No? Navigate to page defined. found khaboom. execute
||
||
\/
has preventDefault been called?
||
||
\/
yes? do nothing because we don't have an end.