Dave
Dave

Reputation: 9157

On click, click something else, prevent default. How do I do this properly with jQuery?

What I want to happen is, when you click a link (id="dontFollow"), it triggers a click on a different link(id="follow") and stops you from following the original link.

This is how I thought it should be done-

$("#dontFollow").click(function(e){
   $("#follow").click();
   e.preventDefault();
});

... but it's not working. Whats wrong with my code?

UPDATE: This is a little more tricky than I originally explained. It appears that I need to "click" on the other link to trigger some other events to cause my page to slide to the anchor. Your suggestions for "window.location" does change the window location but it's not triggering my slide events.

Upvotes: 0

Views: 1518

Answers (5)

AndreasKnudsen
AndreasKnudsen

Reputation: 3481

I don't think you can "click a link" programmatically, you can however navigate by setting window.location.href

$('#dontFollow').attr('href','#').click(function(){
  window.location.href = $('#follow').attr('href');
});

Upvotes: 1

user113716
user113716

Reputation: 322492

Your code is correct. Using e.preventDefault() will prevent you from following the link being clicked.

You have't stated what specifically isn't working, but if you're trying to visit the href of the other link, then do this:

$("#dontFollow").click(function(e){
   window.location = $("#follow").attr('href');
   e.preventDefault();
});

Upvotes: 0

Bryan A
Bryan A

Reputation: 3634

Simply have the function return false;

Upvotes: 1

Gregg B
Gregg B

Reputation: 13727

just return false

Upvotes: 2

wajiw
wajiw

Reputation: 12269

$("#dontFollow").click(function(){
   window.open($("#follow").attr('href'));
   return false;
});

Upvotes: 2

Related Questions