brunodd
brunodd

Reputation: 2584

Jquery on focus show div

When I click on the input, it shows the div on both fields. I want the div to appear on the selected input only.

jsfiddle

$('.example').focus(function() {
    $('div.tip').show();
    $(document).bind('focusin.tip click.tip',function(e) {
        if ($(e.target).closest('.tip, .example').length) return;
        $(document).unbind('.tip');
        $('div.tip').fadeOut('medium');
    });
});
$('div.tip').hide();

Upvotes: 0

Views: 4944

Answers (3)

Mehdi
Mehdi

Reputation: 4318

If we fix the nested <div> like this jsfiddle

<div>
    <label for="example">Text:</label>
    <input class="example" name="example" type="text" maxlength="100" />
    <div class="tip">
        Some text...
    </div>
</div>

This should work:

$('.example').on('blur', function() {
    $('div.tip').fadeOut('medium');
});
$('.example').on('focus', function() {
    $(this).siblings('div.tip').show();
});
$('div.tip').hide();

Upvotes: 1

Amit.rk3
Amit.rk3

Reputation: 2417

Jquery .next() or .closest doesn't work between input and divs. So you may need a workaorund like below

Fiddle link

$('.example').focus(function () {
    $('div.tip').hide();
    var i = 0;

    $('.example').each(function () {
        if ($(this).is(":focus")) {
            $($('.tip')[i]).show();
        }
        i++;
    })

    $(document).bind('focusin.tip click.tip', function (e) {
        if ($(e.target).closest('.tip, .example').length) return;
        $(document).unbind('.tip');
        $('div.tip').fadeOut('medium');
    });
});
$('div.tip').hide();

Upvotes: 1

David Jones
David Jones

Reputation: 4305

I would do something like this

As you can see I have added an ID to each div that you want to show that relates to the input you have clicked so you can have more flexibility of where the element is places in the DOM.

Also it hides all the divs that are not relevant to the current input.

I have also moved the div's outside the p tags to make the HTML valid, as suggested in the comments.

$('.example').focusin(function() {
    $('.tip').hide();
    $('#tip-'+$(this).attr('id')).show();
});
$('div.tip').hide();

Upvotes: 2

Related Questions