user2166577
user2166577

Reputation:

How to block a stop a link from working using preventDefault() (or something similar)?

<script>
function test() {
var name=prompt ("Some question / text")
if (name.toLowerCase()=="TextToBlock") {
alert ("text");
name.preventDefault();
}
else {
}
}
</script>


<body>
< a id="link"  onclick="test()" href="http://www.example.com">Text</a>
</body>

I'd like it to be so that if someone typed in "TextToBlock" in the prompt box it would prevent the user from going to the link location.

Thanks.

Upvotes: 1

Views: 182

Answers (2)

eyecatchUp
eyecatchUp

Reputation: 10560

All you need in just one line:

<script>
  function test() {
    return "texttoblock" === prompt("Some question / text").toLowerCase() ? (window.event.preventDefault(), alert("text"), !1) : !0
  };
</script>

<body>
  <a id="link" onclick="test()" href="http://www.example.com">Text</a>
</body>

Demo: JSFiddle


PS: If you want to prevent loading the link when a user types "TextToBlock" (case-sensitive), in test function change "texttoblock" to "TextToBlock" and remove the .toLowerCase().

Upvotes: 0

Amy
Amy

Reputation: 7466

You just need to pick up the event object from the click handler. (See fiddle http://jsfiddle.net/amyamy86/pJvZd/)

function test(event) {
    event = event || window.event;
    var name = prompt("Some question / text")
    if (name.toLowerCase() === "texttoblock") {
        alert("text");
        event.preventDefault();    // block link from working
    } else {
    }
};

<body>
    <a id="link"  onclick="test()" href="http://www.example.com">Text</a>
</body>

Read more about Javascript event objects: http://javascript.info/tutorial/obtaining-event-object

Also, use === for strict comparisons. And also since you converted name .toLowerCase() you should be comparing it to texttoblock in lowercase.

Upvotes: 1

Related Questions