18

I have following html+ js code:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>

<a href="#" id=key onclick="func(0)">foo</a>

</body>

<script type="text/javascript">
function func(k){
    alert(1);
    return false;
}   
</script>
</html>

Can you explain how to refactor following code that after click on href code func executes but # doesn't add to the URL and page shouldn't be reload?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

8 Answers8

27

Use javascript:void(0); instead of # as follows:

<a href="javascript:void(0);" id=key onclick="func(0)">foo</a>

Using the void operator in the href attribute of the anchor tag ensures that the browser will still display it the same way as any other anchor tag (depending on your CSS settings, this is generally a blue underlined text that changes the cursor when hovered over... etc), prevents the page redirecting to a URL that's just effectively the same page but with the added hash character (#) at the end of the address line, while also makes your onclick event to fire.

benomatis
  • 5,536
  • 7
  • 36
  • 59
6

You can simply remove the href attribute:

<a id='key' onclick="func(0)">foo</a>
Ben Hull
  • 157
  • 8
  • 1
    Is that valid HTML? I thought an `a` tag had to have an `href` attribute. – acfrancis Oct 20 '14 at 20:30
  • on another note, i think this one will use the `cursor:text` on the anchor tag... i know it can be set with css afterwards, just sayin'... – benomatis Oct 20 '14 at 20:35
  • Seems to validate fine in HTML4 strict and HTML5. @webeno good point - you can use `cursor: pointer` to make the a tag use the pointer cursor again. – Ben Hull Oct 20 '14 at 20:38
6

Change it to:

                            vvvvvvv
<a href="#" id=key onclick="return func(0)">foo</a>
qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • i personally like this one the best ;) do you know why this one is preventing the `#` appearing in the address line? – benomatis Oct 21 '14 at 05:49
  • @webeno When you return false in a click handler it stops the default action from happening, in the case of a hyperlink: going to the url (in this case `#`) – qwertymk Oct 21 '14 at 16:41
  • curious why `return function` would actually mean to the default to return false then run the function, a shorthand i never knew how it worked... – benomatis Oct 21 '14 at 19:27
  • 2
    because `func(0)` returns false so `onlick="func(0)"` is the same same `onclick="false"` and `onclick="return func(0)"` is the same as `onclick="return false"` – qwertymk Oct 21 '14 at 19:32
  • actually, i still don't get it... why is `return func(0)` "more" false than `func(0)` in itself? i guess i'll have to try and train myself on js a bit more... :) – benomatis Oct 21 '14 at 20:12
  • 1
    @webeno think of it this way: `fn = function() { 1 }; alert(fn())` vs `fn = function() { return 1 }; alert(fn())` – qwertymk Oct 21 '14 at 20:32
  • it looks clear, but i still don't see why it would result in not returning false if you don't use `return`... but i think i miss the basics of js, as i'm self-taught, i don't necessarily understand what i'm doing, i just know that it works... :) – benomatis Oct 21 '14 at 20:41
1

To be more semantically correct I would be using a button with the following onclick:

<button id=key onclick="return func(0)">foo</button>

This way there is no need to hack around with e.preventDefault / return false.

nickspiel
  • 5,170
  • 6
  • 33
  • 48
  • button looks not like link – gstackoverflow Oct 20 '14 at 20:42
  • 1
    Well an a tag is not meant to be used in this fashion. It is up to you if you want to spend a little extra time styling the button. This is very simple to fix with CSS and will mean your mark up is valid and you wont need to produce hacks to get the browser to work the way you want. Up to you. – nickspiel Oct 20 '14 at 20:47
  • Oh and BTW not cool to down vote my answer because you're too lazy to follow web best practise. – nickspiel Oct 20 '14 at 20:48
  • If you can provide these lines I will upvote you answer – gstackoverflow Oct 20 '14 at 20:51
  • That was not part of your original question, my answer answers your question with industry best practise. The very least you could do would be to remove the down vote. – nickspiel Oct 20 '14 at 20:53
  • Note, In my original question I use word hyperlink. – gstackoverflow Oct 21 '14 at 07:08
0

I think you forgot the quotation marks in "key"

<a href="#" id="key" onclick="func(0)">foo</a>

Sergio Toledo Piza
  • 793
  • 1
  • 6
  • 27
  • 1
    don't think adding the quotation marks is going to remove the hash from the link... on the other hand, this is allowed in HTML and should not be a problem, read more here (unquoted attribute values): https://mathiasbynens.be/notes/unquoted-attribute-values – benomatis Oct 20 '14 at 20:41
  • Direct link to the section quoted on the website I referenced in my previous comment: https://html.spec.whatwg.org/multipage/introduction.html#a-quick-introduction-to-html:syntax-attributes – benomatis Apr 29 '19 at 10:28
0

Inside func, you could do:

func(event){ event.preventDefault(); /* More code here! */ }

preventDefault will prevent redirection, after that line, you could add any logic you want.

However, if you don't want a redirect, it is recommended to use a button instead of an a

nvidot
  • 1,262
  • 1
  • 7
  • 20
Mártin Alcalá
  • 4,589
  • 1
  • 7
  • 13
0

If we want to stop redirect. We have have to return false.So we can do like that: html:

 <a onclick="return check()" href="{% url 'app_name:delete_url' item.id %}" title='Delete Item' class="btn btn-sm btn-outline-success mr-1"
 <i class="fa fa-trash"></i></a>

script:

function check(){
    if (confirm("Do you want to delete?") == true) {
        return true;
    } else {
        //cancle 

       return false
        
    }
}
Shaiful Islam
  • 335
  • 2
  • 12
0

I have seen in a demo template one has used this "#!".

<a href="#!">Link</a>

I don't know why its working but it's working.

طلحة
  • 375
  • 4
  • 8