blue-sky
blue-sky

Reputation: 53916

How to invoke a 'click' when user clicks on href

I'm trying to fire an alert when a user clicks on an anchor tag, but the alert is not being fired. The code I am trying is below.

http://jsfiddle.net/NLdTJ/

<a id="collapse"> Collapse</a>

$(function(){
  $('#collapse').click(function(){
      alert('here');
  });
});

Upvotes: 0

Views: 65

Answers (6)

pete
pete

Reputation: 25091

There's absolutely nothing wrong with your code. It will work when you pick a jQuery library from the Framework options on the left side of jsFiddle.

Updated fiddle to include framework.

Upvotes: 0

ama2
ama2

Reputation: 2681

It should work fine, just change the framework on JSFiddle to include JQuery and run on DOMReady

Upvotes: 0

ijason03
ijason03

Reputation: 581

<a id="collapse" href="#" onclick="alert('here');"> Collapse</a>

Upvotes: 0

davids
davids

Reputation: 6371

Your code is ok, but you weren't loading jQuery in your fiddle.

http://jsfiddle.net/NLdTJ/3/

$(function(){
  $('#collapse').click(function(){
      alert('here');
  });
});

P.S.: I've attached your code again because SO didn't let me post the answer with just a link to jsfiddle and no code :)

Upvotes: 3

Shyju
Shyju

Reputation: 218942

Make sure you prevent the default click behaviour of a link.

$(function(){
  $('#collapse').click(function(e){
      e.preventDefault();
      alert('here');
  });
});

Working sample : http://jsfiddle.net/NLdTJ/15/

Upvotes: 3

syazdani
syazdani

Reputation: 4868

You need to have a href before a tags become hyperlinks. Otherwise they are just anchors. TO fix it you should do the following:

    <a id="collapse" href="#"> Collapse</a>

    $(function(){
       $('#collapse').click(function(){
          alert('here');
       });
    });

Hope that helps.

(I also assumed jQuery, but your fiddle was set up with mooTools, not sure if it was on purpose. Here is my fix: http://jsfiddle.net/NLdTJ/13/)

Upvotes: 3

Related Questions