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 ?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With