views:

48

answers:

3

Hi guys,

I need to invoke an event (for example - display alert) if a user presses on a link (not clicks) - and I don't want it to redirect him to another page. In other words - when a user clicks a link - everything is as usual but when the user presses the link, just the event happens (the alert is displayed) and the user will stay in my page. Is this possible?

By saying press I mean that a user presses on a link for at least one second.

Thanks.

A: 

Define press.

You probably want to use either the mousedown or keypress event, depending on what you mean. (The latter case would probably involve checking the event to make sure it was the enter key that was used)

David Dorward
I think he ment mouse down, as the href="javascript:alert(...)" will fire on mouseup, and using onmousedown with empty href will refresh the page (and no href will render no link, just the test)
Ehrann Mehdan
by saying "press" I mean that a user presses on link for at least a second.
Alex1987
So update the question, this means a totaly different answer
Ehrann Mehdan
A: 

What I understood is that you want:

user pressed the link -> fire an action, but don't redirect the browser User clicks the link (mouse up over the same object where you pressed the button) -> redirect to a different page

The following code might help

<html>
<head>

    <script type="text/javascript">
function mouse_pressed(){
    alert('pressed button');
}
function goToLink(url){
    window.location = url;
}
</script>
</head>
<body>

<label onclick="goToLink('http://www.google.com');" onmousedown="mouse_pressed();" >text</label>
<body>
</html>
Dani Cricco
I tested it on safari and got the same result in both cases - I get that alert and get redirected to google
Alex1987
Label?! How on earth does using a label make sense here? (And build on things that work: http://icant.co.uk/articles/pragmatic-progressive-enhancement/ )
David Dorward
I uses label just to manage the events (onclick, onmousedown). It can be replaced by any other html tag that allows those events.
Dani Cricco
@Alex1987, then you need to define what "press" means
Dani Cricco
A: 

After you refined your question, this code does what you are looking for:

<script>
var timeout;
function onMouseDown(){
    timeout = window.setTimeout("alert(1)",1000);
}
function onMouseUp(){
    window.clearTimeout(timeout);
}
</script>

<a href="#" onmousedown="onMouseDown();return false;" onmouseup="onMouseUp();return false;">click</a>

Notes:

  • The return false causes the href not to be executed,
  • The timeout set and clear makes sure that a press of less than a second, won't fire the event

This will fire the alert if the user presses and holds the mouse over 1 second (1000 ms) on the link.

Ehrann Mehdan