0

I have a link like this.

<a href="board.php?id={$id}" onclick="javascript:parent.$.fancybox.open({href : 'board.php?id={$id}', type: 'ajax'});">

If the JavaScript is disabled, the browser can use the href value to load the page. But, if the JavaScript is enabled, the onclick and the href will work together. How can I prevent this? I want the href not to work when the JavaScript is enabled.

1
  • 1
    perhaps "this.preventDefault();" or "return false;" might work (inside the onclick) but I personally would handle the click event inside a javascript file or outside of the anchor. Commented Apr 26, 2015 at 12:37

2 Answers 2

4

You need to use event.preventDefault(); or return false;.

<a href="board.php?id={$id}" onclick="javascript:parent.$.fancybox.open({href : 'board.php?id={$id}', type: 'ajax'});return false;">

OR Using jQuery:

$('a').on('click', function(e) {
    e.preventDefault(); // Stop redirect
    // Your code here
});
Sign up to request clarification or add additional context in comments.

Comments

1

You should use either event.preventDefault() or a false return value:

<a href="board.php?id={$id}" onclick="javascript:parent.$.fancybox.open({href : 'board.php?id={$id}', type: 'ajax'});event.preventDefault();">

or 

<a href="board.php?id={$id}" onclick="javascript:parent.$.fancybox.open({href : 'board.php?id={$id}', type: 'ajax'});return false;">

Really, though, you shouldn't use inline event handlers like this. You should give your link an id or class and attach the handler to it like this:

<a href="board.php?id={$id}" id="myElement">something</a>
<script>
    document.getElementById('myElement').onclick = function () {
        parent.$.fancybox.open({href : 'board.php?id={$id}', type: 'ajax'});
        event.preventDefault();
    };
</script>

This will make it much easier to read and maintain down the road.

Here's a simple jsFiddle demo.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.