I have found a solution, but im not secure is it valide. Pleas help!
There is not so easy why the people think.
The thing is, it should be a solution for existing websites. No new coding is needed. Only insert the function myFunction()
. onclick="myFunction()" is always present
. And its only possible to put JS code in the head
(not in the footer), because for this a custom <script>
is always loaded via PHP in the webpages.
First, a methode with only code a new function
with javascript:void(0);
The running code snippet function here don't work by me. Below a JSFiddle.
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
document.getElementById("demo").removeAttribute("target");
document.getElementById("demo").href = "javascript:void(0);";
}
}
<!DOCTYPE html>
<html>
<body>
<a id="demo" href="https://www.example.com" onclick="myFunction()" target="_blank" rel="nofollow">example.com</a>
</body>
</html>
The code:
<!DOCTYPE html>
<html>
<body>
<a id="demo" href="https://www.example.com" onclick="myFunction()" target="_blank" rel="nofollow">example.com</a>
<script>
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
document.getElementById("demo").removeAttribute("target");
document.getElementById("demo").href = "javascript:void(0);";
}
}
</script>
</body>
</html>
JSFiddle: https://jsfiddle.net/dLp8qtcm/
Second, a solution with preventDefault(). Consider the event
instead a this
. For this a edit of the webpages is needed for inside the event
in onclick="myFunction(event)"
.
Thanks for the hints with the preventDefault()
, but the examples in the answers don't work by me. Here is a working solution.
The running code snippet function here don't work by me. Below a JSFiddle.
function myFunction(e) {
var confirmresult = confirm("Press a button!");
if (confirmresult == true) {
// OK = go away!
} else {
// Cancel = stay here!
e.preventDefault();
}
};
<a href="https://www.example.com" onclick="myFunction(event)" target="_blank" rel="nofollow">example.com</a>
<a href="https://www.example.com" onclick="myFunction(event)" target="_blank" rel="nofollow">example.com</a>
<script>
function myFunction(e) {
var confirmresult = confirm("Press a button!");
if (confirmresult == true) {
// OK = go away!
} else {
// Cancel = stay here!
e.preventDefault();
}
};
</script>
JSFiddle: https://jsfiddle.net/osanthdq/
EDIT: The matter is a little bit complex. I have explained it here: Event keyword in js