ElliotDurden
ElliotDurden

Reputation: 49

how to check if a link was clicked?

Here is my problem. I am editing a website that is generating all the content of the website in a loop from the server side to the PHP and then I am asked to manipulate the website using jQuery.

The question here is that, a lot of link tags that exists on the website have no IDs associcated with them. So I am asked to solve a problem, where if one of the link tags is clicked, some jQuery logic takes place.

In my case, if link tag with text "See All" is clicked. I am supposed to carry out some code execution but how exactly do I write it?

Is it as simple as writing:

$("a:contains('See All')").click(function() {
  // do something
});

because that doesn't seem to be working. Any help?

Upvotes: 2

Views: 8516

Answers (3)

R.M.
R.M.

Reputation: 1

How about using a link shortening service (e.g. Google's https://goo.gl/, or click to tweet's clicktotweet.com, free for 5 and paid there after). The use the shortened link.

This will keep track of the number of times the link is clicked.

Now what you were looking for, no

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

Exact matching for See All and so on

$("a")
     .filter(function() {   // apply filter() to for exact text matching
          return $(this).text() == 'See All';
     }).click(function(e) {
          // To prevent page reload you need .preventDefault()
          e.preventDefault();
          alert('hello');
     });

DEMO

Check containment of See All (not exact match)

$("a").filter(function() {
    return $(this).text().match('See All'); // a little change here
}).click(function() {
    alert('hello');
});

or just use :contains()

$('a:contains(See All)').on('click', function() {
   alert('Hello');
});

DEMO

Some extra note

If your links generate after DOM ready then you need to try with ".on" event binding like:

$('#container').on('click', 'a:contains(See All)', function() {
  alert('Hello');
});

and in case the client was using jQuery v-1.7, then try ".delegate" event as follows:

$('#container').delegate('a:contains(See All)', 'click', function() {
  alert('Hello');
});

Upvotes: 4

Andreas Wong
Andreas Wong

Reputation: 60516

Have you tried removing the ' in 'See All'?

Also, to make sure that it doesn't redirect the users to the link in href, use e.preventDefault()

$("a:contains(See All)").click(function(e) {
  e.preventDefault();
  // do something
});

http://jsfiddle.net/99LMh/

Upvotes: 1

Related Questions