I'm using this in my HTML:
<a href="#" onclick="preload('12345');return false;">Click</a>It calls the function preload() on an external js-file and works fine so far.
But i have dozens of those links and would like to remove alle those "return false" and put only one directly inside the preload()-function in the js-file.
But it will always be ignored?! Does the "return false" really only work inside the onclick="..."?
15 Answers
function preload () { // some code return false;
}
<a href="#" onclick="return preload('12345');">Click</a>or use addEventListener
For example:
<a href="#">Click</a>
<script type="text/javascript"> document.querySelector('.link').addEventListener('click', function (e) { // some code; e.preventDefault(); }, false);
</script> 1 Putting return false; in the inline onclick attribute prevents the default behavior (navigation) from occurring. You can also achieve this by clobbering the onclick attribute in JavaScript (i.e. assigning the .onclick property to be a function that returns false), but that's frowned upon as old-fashioned and potentially harmful (it would overwrite any additional event listeners attached to that event, for example).
The modern way to prevent the <a> element's default click behavior from occurring is simply to call the .preventDefault() method of the triggering event from within the attached event listener. You can attach the listener the standard way, using .addEventListener()
Some examples:
// this works but is not recommended:
document.querySelector(".clobbered").onclick = function() { return false;
};
// this doesn't work:
document.querySelector(".attached").addEventListener("click", function() { return false;
});
// this is the preferred approach:
document.querySelector(".attachedPreventDefault").addEventListener("click", function(e) { e.preventDefault();
});<a href="/fake" onclick="return false;">If you click me, I don't navigate</a><br/>
<a href="/fake">If you click me, I don't navigate</a>
<br/>
<a href="/fake">If you click me, I navigate</a>
<br/>
<a href="/fake">If you click me, I don't navigate</a> I think if you put it into the preload function and in the onclick event just put return false will work. Maybe you've tried this code?
<a href="#" onclick="return preload('12345');">Click</a> Try to put the return false clause into the inline function:
<input onclick="yourFunction();return false;"> I would maybe suggest not using onClick() and instead using similar jQuery.
2