aayushagra
aayushagra

Reputation:

How to implement a generic click event for anchors

I have a PHP script that throws out a bunch of buttons (Format in case it is needed):

<a class="ClassInfo" id="id">Name</a>

The file is retrieved dynamically and there can be as many buttons as possible, maybe none, and maybe a million (unlikely though).

I need to use JavaScript for this and can't just redirect the user to another website (mostly because the operation is repeated heavily and gets EXTREMELY tedious.).

Is it possible for me to use some combination of JavaScript + jQuery to detect which button was pressed and do an operation appropriately?

Example of what I am hoping for is this:

Now is it possible for me to detect which button was clicked?

Upvotes: 2

Views: 4456

Answers (4)

David Barker
David Barker

Reputation: 14620

For a jQuery solution you can add a click event listener to your element a.ClassInfo:

$('a.ClassInfo').click(function(event) {
    alert(this.id);
});

// ES6
$('a.ClassInfo').click(event => alert(this.id));

Or better yet, use event bubbling to your advantage with .on

$(document).on('click', 'a.ClassInfo', function(event) {
    alert(this.id);
});

// ES6
$(document).on('click', 'a.ClassInfo', event => alert(this.id));

Event bubbling is very useful if you dynamically generate HTML. It avoids having to bind/rebind event listeners to elements when they're added to or removed from the DOM if you bind to a lower level element (in this case document).

Upvotes: 3

Reedwanul Islam
Reedwanul Islam

Reputation: 335

You can try something like this;

$( ":button, :submit" ).click(function(){
    var id = $(this).attr('id');
    alert('Call post for:'+id);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="t1">T1</button>
<input type='button' value='T2' id='T2' />
<input type='submit' value='T3' id='T3' />

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

Assuming the links in question all have the same class (or a known list of classes), and that you can use jQuery:

$('a.ClassInfo').on('click',
  function(event) {
    event.preventDefault();

    var id = this.id;

    console.log('ClassInfo ' + id + ' was clicked');

    // continue with Ajax from here
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="ClassInfo" id="id1">Name 1</a> -
<a class="ClassInfo" id="id2">Name 2</a> -
<a class="ClassInfo" id="id3">Name 3</a>

Upvotes: 2

Quentin
Quentin

Reputation: 943108

The target property of the event object will tell you which element was clicked on.

document.addEventListener('click', function (e) {
  var target = e.target;
  if (target.tagName && target.tagName.toLowerCase() == "a") {
    alert(target.id);
  }
});

See a live demo

Upvotes: 5

Related Questions