raj raj -3 years ago 71
HTML Question

Anchor link takes two clicks to fire the event

The HTML:

<asp:TextBox ID="dataTextBox" MaxLength="10" runat="server"></asp:TextBox>

<a class='new_message' onclick='focusMethod();' tabindex='-1' href='#dataTextBox"> New Message</a>";


Jquery function:

function focusMethod() {
$('[class=new_message]').click(function (e) {
e.preventDefault();
$($(this).attr('href')).focus();
});
}


When i click the anchor link the focus should go to the input text box. But it is taking 2 clicks to perform.

My scenarios are:


  1. onclick is used in anchor tag to prevent default behaviour i.e firing the href.

  2. I am building an accessible form so i need the href with value (so i wont be able to use href="#")

  3. If i use just the click event handler without the function it is not being fired( instead href is fired and focus is not going to textbox)



It takes 2 clicks because the function focusMethod is fired first and then event handler is attached.
Is there any way to avoid performing the function "focusmethod' and only perform click event handler?

Answer Source

Because your method focusMethod is binding a new click event which is then executing next time you click that element. Just remove the inline click event onclick='focusMethod();' as it's not needed. Then instead of a function you can just do:

$('[class=new_message]').click(function (e) {
    e.preventDefault();
    $($(this).attr('href')).focus();
});

Edit:

Since your element is dynamic you need to use $(document).on(...) instead, otherwise the selector $(...).click(..) isn't going to find the element as it wouldn't exist when setting up the click event binding.

Below is a basic example with the element being dynamically created:

$(document).on("click", "[class=new_message]", function (e) {
    e.preventDefault();
    console.log("clicked");
    $($(this).attr('href')).focus();
});

$("body").html("<a class='new_message' tabindex='-1' href='#dataTextBox'> New Message</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download