santa
santa

Reputation: 12512

Simulate click with jQuery

I have a script that assigns tabindex to visible elements on a page. Most of those are form elements but I also needed to add a way to add a div that I use to show/hide a section.

<span class="tabInto">Show/Hide</span>

I do this with jQuery

$(':input:visible, .tabInto').each(function (i) {
    $(this).attr('tabindex', i + 1);
});

So, when I tab through the form fields I am able to tab into that span as well. Now I need to be able to simulate click action, to expand hidden section, by using keyboard when I am focused on that span. How Can I do that? Is it usually done with Enter or Space bar?..

Upvotes: 1

Views: 161

Answers (2)

James Montagne
James Montagne

Reputation: 78650

If you are using an anchor tag (with an href), then this is default functionality. Hitting the enter key while the element has focus will trigger the click handler.

You can simulate this same functionality with a span in the following way:

$("span").click(function () {
    alert("click span");
});

$("span").keypress(function (e) {
    if (e.keyCode == 13) {
        $(this).click();
    }
});

http://jsfiddle.net/dLmyV/

Upvotes: 1

Joren
Joren

Reputation: 3297

Using $(".tabInto").trigger("click")

This way you fire the 'click' event on the tabInto class.

Source: http://api.jquery.com/trigger/

Upvotes: 0

Related Questions