javascript - How do widgets that put HTML in a HTML textbox (tags, Google+ Invite, etc) work? -
i find hard myself started in topic can write own widgets own needs. how can combine plain text , html elements (links, images), seen everywhere on web (google, facebook, etc), in html textbox in way still behaves simple text (i. e. deleteable backspace)?
how work? underlying "trick"?
ok, question indicates need starting point, lets start basic html such div
, ul
, , input
<div class="mytags"> <ul id="tags"> <li class="nd"><input type="text" id="taginput" placeholder="add tags..."/></li> </ul> </div>
now lets write jquery handle tagging:
$('#taginput').keypress(function(e){ if (e.keycode === 13) { tag = $(this).val(); if(tag.length > 0){ var newli = $('<li></li>').text(tag); } $('#tags').append(newli); $(this).val(''); } });
this jquery snippet listens keypress event on provided input called taginput
enter key goes keycode 13
hence, if been hit take value of textbox , and create new li element go , append ul.
what missing here how make ul looks horizontal, starting css used:
#tags{ float: left; min-height: 10px; min-width: 100px; margin:0px; padding: 0px; list-style-type: none; text-align: center; background-color: #fff; border: 1px solid #ccc; } #tags li { display: inline-block; padding: 10px;} #taginput{background: none; border: none;}
which make ul horizontal, , delete background input , adds border , background ul, lovely trick specially placeholder being available, backspace deleting process simple too, take previous jquery snippet , add following code it:
$('#taginput').keyup(function(e){ if(e.keycode === 8 && $(this).val().length<=0){ $('#tags li:last').not('.nd').remove(); } });
which check keycode 8
backspace, note: people recommend listen keycode 46
delete
, you. , check input value should empty delete last inserted tag. wrapping have following fiddle check. start point can whatever want tag styles , many other fancy stuff.
hope helped. disclaimer: previous code not copy pasted, , there point clarification.
update also, adding outline:0
input make more real, see fiddle
#taginput{background: none; border: none; outline:0}
Comments
Post a Comment