Recent Posts

Showing posts with label tag. Show all posts
Showing posts with label tag. Show all posts

Rename the content inside a tag and confirm with jQuery

This examples target one simple container and change his name and then make the confirmation:

For this you need to identify the relevant h2/textarea

You also should nest your handler binding because each time your try to edit, you add a new handler

HTML:

<div class="rename">
     <h2 class="replaceble">Dell PC</h2>
 <a href="#" class="replace">Rename</a>
 <a href="#" class="confirm">Confirm</a>

</div>
<div class="rename">
     <h2 class="replaceble">Dell PC</h2>
 <a href="#" class="replace">Rename</a>
 <a href="#" class="confirm">Confirm</a>

</div>
<div class="rename">
     <h2 class="replaceble">Dell PC</h2>
 <a href="#" class="replace">Rename</a>
 <a href="#" class="confirm">Confirm</a>

</div>
JavaScript:

(function ($) {
    $.fn.changeElementType = function (newType) {
        var attrs = {};

        $.each(this[0].attributes, function (idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });

        this.replaceWith(function () {
            return $("<" + newType + "/>", attrs).append($(this).contents());
        });
    }
})(jQuery);

$(document).keypress(function (e) {
    if ($('textarea:visible')) {
        if (e.which == 13) {
            alert('You pressed enter!');
            $("textarea").changeElementType("h2");
            $('.replace').css('opacity', '1');
        }
    }
});

$('.replace').on('click', function () {
    var container = $(this).closest('.rename')
    container.find('h2').changeElementType("textarea");
    $(this).hide();
    $(this).next('a').show();
});

$('.confirm').on('click', function () {
    var container = $(this).closest('.rename')
    var $textarea = container.find('textarea');

    $(this).hide();
    $(this).prev('a').show();
    $textarea.html($textarea.val()).changeElementType("h2");
});
CSS:

textarea {
    height: 30px;
    overflow: hidden;
    padding:0;
    border: 0;
    background:none;
    resize: none;
    font-size: 24px;
    text-align: center;
    font-family: $font-family;
    color: $white;
    height:30px;
}
div.rename {
    border:1px solid red;
    float:left;
    width:60%;
    margin:20px;
}
h2 {
    height:30px;
    color:red;
}
.confirm {
    display:none;
}