0

I have javascript that uses 'href="#"' to call a function when it's clicked. The problem is that when I run it on Chrome, I need 2 Back presses to return to the referrer page, but on Opera, I only need 1 Back press.

I read the details about using 'href="#"' here: What is href="#" and why is it used?

here is my test code:

<p>
    <script type="text/javascript">
        function testOnClick(){
            document.write("onClick() support was detected!<br>");
        }
    </script>
</p>

Clicking on the link should clear the screen and display progress text<br />
<a  onclick="testOnClick();" href="#!">
    Click here to test onClick
</a>
Community
  • 1
  • 1

4 Answers4

2

You might need to use event.preventDefault();

function testOnClick(event) {
    event.preventDefault();
    document.write("onClick() support was detected!<br>");
}

It prevents your navigator to navigate to the # link, thus, having to press back.

LeonardDrs
  • 625
  • 7
  • 8
0

You can also get similar functionality by using a different element and making it look like a link. If you aren't navigating the user to a different section of the page or a new page, for example, you probably should be using the <a> tag.

Here's a fiddle for what I mean: http://jsfiddle.net/2ph2d2gd/

The use case for this would be to open a modal, or do some other action that doesn't necessarily navigate the user anywhere. I don't know your specific circumstances, so you may or may not want to use something like this.

Note: I used alert instead of document.write because jsfiddle doesn't allow the latter.

HTML:

Clicking on the link should clear the screen and display progress text<br />
<span class="link" onclick="testOnClick();">
    Click here to test onClick
</span>

CSS:

.link{
    text-decoration:underline;
    color:blue;
    cursor:pointer;
}

Javascript:

function testOnClick(){
    alert("onClick() support was detected!");
}
ps2goat
  • 8,067
  • 1
  • 35
  • 68
0

I've had good results leaving the href blank in this scenario. It doesn't reload the page with "#" at the end of the URL and events still fire.

I'm not sure how well that works with JS onclick, but you could replace that with jQuery.

<script type="text/javascript">
    $(function() {
        $("#link").on("click", function() {
            alert("click");
        });
    });
</script>
<a id="link" href="">
    Click here to test onClick
</a>
Robin French
  • 675
  • 6
  • 17
0

If you use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.

OR

Use href="javascript:void(0)"

More information about why can be found in this question

Community
  • 1
  • 1
raphaelgontijolopes
  • 1,263
  • 2
  • 9
  • 10