Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anchor tag jQuery Click

I have an Anchor Tag like this

    <a href="javascript:anchorScr()" id="anch1" class ="af-link"/>

It is taking me two clicks on the anchor tag to respond to the javascript function anchorScr();

function anchorScr() {
jQuery('a').click(function (event) {
    var id = $(this).attr("id");
    alert(id);
   });
 }

Am I doing something wrong? Why my anchorScr() is not called on the first click ?

like image 518
Suave Nti Avatar asked Dec 18 '11 10:12

Suave Nti


People also ask

Can we use Onclick in anchor tag?

Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.

How do you trigger an anchor click?

If you are trying to trigger an event on the anchor, then the code you have will work I recreated your example in jsfiddle with an added eventHandler so you can see that it works: $(document). on("click", "a", function(){ $(this). text("It works!"); }); $(document).

What is trigger click in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

How do you call a click method in jQuery?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


1 Answers

This calls the anchorScr function when the anchor is clicked:

href="javascript:anchorScr()"

The function then attaches a click event handler to all a elements.

Remove the href and just have this:

jQuery('a').click(function (event) {
    var id = $(this).attr("id");
    alert(id);
});

The code will execute - attaching the click event handler to all a elements. You should probably only run this on ready() to ensure that the page has fully loaded into the DOM.

like image 140
Oded Avatar answered Sep 27 '22 22:09

Oded