-1

I know that <a href="javascript:void(0)">Link</a> will just do the job,

but what I intend to do is to specify a href, but will not jump to it when being clicked, just like:

<a href="http://mydomain.com" onclick="...">Link</a>

When I click on this link, I'd just like the onclick is invoked, whereas href is just a 'show' without jumping to http://mydomain.com.

How could this be done by javascript or css? Thanks a lot!

Judking
  • 5,231
  • 10
  • 46
  • 76

3 Answers3

1

add class to the link, for example: class="not-jump"

then in jQuery add listener:

$( ".not-jump" ).click(function(e) {
    e.preventDefault();
});

That should do the trick.

Andrei Konstantinov
  • 6,073
  • 4
  • 34
  • 55
1

There are a few ways you can do this. If you must fulfill the answer within the HTML then:

<a href="mydomain.com" onclick="function(e){e.preventDefault()}">click here</a>

But better practice is to follow Andrew Spartar's solution and separate the JavaScript using a class or other selector.

dSkech
  • 169
  • 4
0

like this:

<a href="http://mydomain.com" onclick="myFunc(event)">Link</a>

JS:

function myFunc(e) {
    e.preventDefault();

   ...
}

and to separate html from js:

<a href="http://mydomain.com" class="somelink">Link</a>

JS:

$(".somelink").on('click', function(event) {
     event.preventDefault();
});
webkit
  • 3,251
  • 1
  • 12
  • 17
  • where does the `event` argument come from? I've already have a string argument for `myFunc`, should I put `event` argument at the second place? – Judking Jun 22 '14 at 08:46
  • the event object can be passed as an argument, it has a bunch of properties and information about the event (click in your case), you can use it's preventDefault() method to prevent the default behavior for that specific event.. you can have it as second argument if you like.. – webkit Jun 22 '14 at 08:58
  • btw, It is definitely recommended to separate your javascript from your html, so I'll update the answer above.. – webkit Jun 22 '14 at 09:00