Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when link is activated - either by click or tab and enter

Just wondering if anyone knows of a way that wiring up jquery to run a function for when a user clicks on a link or tabs to a link and hits enter.

I want to intercept that activation of a link and perform an action before the page is changed, but I want to do it in either case.

like image 679
vdhant Avatar asked Apr 23 '09 12:04

vdhant


People also ask

How do you check if an event has been triggered in JavaScript?

To check if event is triggered by a human with JavaScript, we can use the isTrusted property. to check if the event is triggered by a human in our event handler callback. e is the event object and it had the isTrusted property. If isTrusted is true , then the event is triggered by a human.

How do you know if a link is clicked?

For websites, you can use Google Analytics. To do this, enable the analytics tools provided by Google and use their measurements to check all your clicked links arriving at the website. If you use marketing channels to mostly drive traffic to your website, this is a good place to start.

Why on clicking the link is not working?

Browser Issues The lack of link-clicking might simply be a browser setting gone awry. If you can, try clicking on a link with a different browser to see if it works. If it does, then your browser settings are probably off and need to be reset. One way to do this quickly is to uninstall and reinstall the browser.


3 Answers

The 'click' event will fire in both cases, this will get you what you want:

$('a').click(function(){
    alert('perform action here');
});
like image 181
pjesi Avatar answered Oct 16 '22 17:10

pjesi


It's pretty simple actually... When pressing enter on an element, it acts as a click in browsers. No need to do anything special.

$('a.links_to_bind').bind('click', function() { 
    /* do your stuff... */
    return false;
});

Edit: If you want the page to change after your actions are complete, you may want to add a conditional statemenet to that return false. Something like:

if(everythings_good) {
    return true;
} else {
    return false;
}
like image 27
KyleFarris Avatar answered Oct 16 '22 18:10

KyleFarris


The following two links provide information about the events in jQuery you want to handle.

jQuery Events/keypress: http://docs.jquery.com/Events/keypress
jQuery Events/click: http://docs.jquery.com/Events/click

like image 1
RuudKok Avatar answered Oct 16 '22 18:10

RuudKok