Boxiom
Boxiom

Reputation: 2305

Append after focused child

I have a div with the ID wrapper, and I am using .append() to insert some content at the end of that div, like this:

$("#wrapper").append('Some divs and input fields');

However, I also want the option to insert a new child after the focused content div in the wrapper.

So if the HTML output looks like this:

<div id="wrapper">
    <div class="content">
        <div class="subcontent">
             First div
            <input type="text" />
        </div>
    </div>
    <div class="content">
        <div class="subcontent">
            Second div
            <input type="text" />
        </div>
    </div>
</div>

And the input field in the first content div is in focus, I want to insert an element after that div, so I get this:

<div id="wrapper">
    <div class="content">
        <div class="subcontent">
             First div
            <input type="text" />
        </div>
    </div>
    <div class="content">
        <div class="subcontent">
            Third div
            <input type="text" />
        </div>
    </div>
    <div class="content">
        <div class="subcontent">
            Second div
            <input type="text" />
        </div>
    </div>
</div>

How would I do this?

Upvotes: 0

Views: 101

Answers (2)

Zee
Zee

Reputation: 8488

As you said

The append function is triggered by pressing enter.

You can try this code. It gets triggered on pressing enter key on input :

HTML:

<div id="wrapper">
    <div class="content">
        <div class="subcontent">
             First div
            <input type="text" />
        </div>
    </div>
    <div class="content">
        <div class="subcontent">
            Second div
            <input type="text" />
        </div>
    </div>
</div>

JS:

    $('#wrapper').on("keyup",'input',function(e){
    if(e.keyCode == 13)
    {
        $(this).closest('.content').after("<div class='content'> <div class='subcontent'>Some div<input type='text' /> </div></div>")
    }
});

Fiddle

Upvotes: 2

Samurai
Samurai

Reputation: 3729

$(':focus') will give you the focused element and closest('.content') gives its ancestor with class content and then you use after to insert the element.

$(':focus').closest('.content').after(whatever_element_you_want_to_add);

Upvotes: 2

Related Questions