jQuery or JavaScript how to highlight selected text in a textarea - javascript

I'm trying to figure out how Facebook does it. I know they use textarea's in there comments and status features, but if I tag someone in a post or something, it will highlight that selection of text in the textarea with a light blue background. I know textarea's or last I knew rather at least, that this wasn't possible with this type of element, so how are they doing it? Whats the technique? anyone have any idea? Im banking on some smoke and mirrors as to how its being done, but not sure how?

Although it is using a textarea in some fashion, the bulk of the magic is done with divs and CSS. I pulled this from Safari's Web Inspector:
<div class="inputContainer">
<div class="uiMentionsInput" id="up84fa_5">
<div class="highlighter" style="direction: ltr; text-align: left; ">
<div style="width: 499px; ">
<span class="highlighterContent"><b>Brandan Lennox</b> is the coolest.</span>
</div>
</div>
<div class="uiTypeahead composerTypeahead mentionsTypeahead" id="up84fa_9" style="height: auto; ">
<div class="wrap">
<input type="hidden" autocomplete="off" class="hiddenInput">
<div class="innerWrap">
<textarea class="uiTextareaAutogrow input mentionsTextarea textInput" title="What's on your mind?" name="xhpc_message_text" placeholder="What's on your mind?" onfocus="return wait_for_load(this, event, function() {if (!this._has_control) { new TextAreaControl(this).setAutogrow(true); this._has_control = true; } return wait_for_load(this, event, function() {JSCC.get('j4f3584ff4f90d07867222385').init(JSCC.get('j4f3584ff4f90d07867222386'));;JSCC.get('j4f3584ff4f90d07867222386').init(["buildBestAvailableNames","hoistFriends"]);JSCC.get('j4f3584ff4f90d07867222383').init({"max":10}, null, JSCC.get('j4f3584ff4f90d07867222385'));;;});});" autocomplete="off" style="height: 48px; direction: ltr; ">What's on your mind?</textarea>
</div>
</div>
</div>
<input type="hidden" autocomplete="off" class="mentionsHidden" name="xhpc_message" value="#[815490222:Brandan Lennox] is the coolest.">
</div>
<div class="attachmentMetaArea"></div>
</div>
The important elements:
The div.highlighter and its descendant span.highlighterContent. Notice that it styles a b element as the highlighted content.
The messy onfocus handler for the actual textarea element. Somewhere in there, it creates a TextAreaControl object, which seems to create an object somewhere else in the DOM, since the textarea content itself is not being updated.
The input[type=hidden].mentionsHidden that submits custom data to the server so it knows who you actually mentioned.
This is totally Facebook specific, but maybe it gives you some ideas for what you'd like to do.

It is not done using a classic textarea. I know it is sounds crazy, but as you type, it generates html where it can mark/highlight keywords and moves an input around so you have a place to type. You can have a look with Firebug to see how it happens in real time.

I've worked up an example based on the html5 demo that allows you to do this. Check it out http://jsfiddle.net/KStst/ This is just telling the browser to make the section editable and it understands basic html features. This is probably not how facebook is doing it but given html5 is "the future" it's probably worth playing with.

Related

How to create a jQuery click handler based on a matching pattern?

I have multiple reason codes (For ex: RC1, RC2...). For each of these reason codes, I want to give the user a text box in which they can enter some comments. Also give them the option of adding multiple text boxes for each reason code.
To allow the user to add a dynamic text box, I have a button which allows the user to do so. If there was only one reason code, I can easily just just append a text box to the pre-existing text box using jquery (Using something like this: JQuery adding class to cloned element).
However since I have multiple reason codes(over 200) it doesnt make sense of having button for each reason code in Jquery. Is there a way for me to search by a basic identifier.
I have pasted the contents of the HTML file generated by my JSP file.
<div id="Reasoncode1">
<div id="inputTextBox_Reasoncode1">
<input type="text" placeholder="Add some text"/><button class="button_Reasoncode1">
+</button>
</div>
</div>
<p>
Reason code2
</p>
<div id="Reasoncode2">
<div id="inputTextBox_Reasoncode2">
<input type="text" placeholder="Add some text"/><button class="button_Reasoncode2">
+</button>
</div>
</div>
My Jquery attempt is:
$(".button_Reasoncode1").click(function() {
$('#Reasoncode1').clone().insertAfter('#inputTextBox_Reasoncode1');
});
$(".button_Reasoncode2").click(function() {
$('#Reasoncode2').clone().insertAfter('#inputTextBox_Reasoncode2');
});
I dont want to do this for each and every reason code, i was wondering if there is a better approach to this.
My JSFiddle: https://jsfiddle.net/mvp71L61/
Assuming all buttons are statically added to the DOM,
$("button[class*='button_Reasoncode']").click(function() {
var rCode = $(this).attr('class').match(/\d+/g)[0];
$("div[id='Reasoncode'+rcode]").clone().insertAfter("input[id='inputTextBox_Reasoncode'+rcode]");
});

Condtionally showing/hiding textarea with select.onchange in Javascript

I'm running up against a wall with something rather simple. I have an "Other:" option on a 'select' element that I am using as a condition for showing/hiding a 'textarea' element. I've got it mostly working despite one strange behavior: no matter what I do the 'textarea' is determined to display when the page loads, despite having 'display="none"' set. If I change to a non-'Other:' option it behaves normally and hides the textarea, and shows it when I select other. The only issue is on loading it defaults to displaying it. I'm sure this is something simple but it is utterly eluding me.
Here's code:
HTML
<div id="otherbox" style="text-align:left; padding:5px; margin:0px 6px;">
<textarea display="none" name="other" id="aboutOther" rows="10" cols="30" wrap="hard">
</textarea>
</div>
Javascript:
<script type="text/javascript">
var slct=document.getElementById("selectMenu");
slct.onchange=function()
{
this.value == "Other:" ? document.getElementById("aboutOther").style.display='block' : document.getElementById("aboutOther").style.display='none';
};
</script>
I included the 'div' on the textarea in case that's relevant (although I suspect it isn't). For full disclosure, that div is nested in another div. Hope that's not important.
Fullest disclosure: I don't know what I'm doing.
You need to use CSS to control the display property. Try to change display="none" to style="display:none;" in your textarea element as "display" is not a default attribute for textarea.

CKEDITOR selection.getStartElement() give wrong element in chrome

I have a main page which has ckeditor to perform some text editing.
ckeditor contains below elements:
<address>Address<address><pincode>123456</pincode>
I try to get focused element as
editorinstance1.focus();
var temp =editorinstance1.getSelection().getStartElement();
or
var temp =editorinstance1.document.getSelection().getStartElement();
when I click before the pincode element's first char
actually I need cursor position like
<pincode>[cursor here]123456</pincode>
the code working fine except chrome
chrome return address element.
how do I get correct element.
Just I checked with HTML it also same problem.(http://jsfiddle.net/z5ABt/2/)
I also reported in code.google.com/p/chromium/issues/detail?id=337757
This seems to be a bug in Chrome, when you click on the first character it focuses the wrong edit area. When you don't use nested contenteditable, it seems to work fine.
<panel>
<div id="address" contenteditable="true">Address</div>
<span contenteditable="true">, </span>
<div contenteditable="true" id="pin">123456</div>
</panel>
Clicking on the 1 will focus the correct edit area.
I can't find a ticket in their bug tracker about this specific issue, but they do have a number of issues regarding nested contenteditable. You might want to make a bug report.
this is a bug in chrome
you may use only like below.
<panel contenteditable="true">
<div id="address" contenteditable="true">Address</div>
<span contenteditable="true">, </span>
<span contenteditable="false"></span>
<div contenteditable="true" id="pin">123456</div>
</panel>

javascript change div html when click span

Ok I have a small question.
I have the following
<div><span class="spanright" onclick"">Update</span><label class="myinfo"><b>Business information:</b></label></div>
What I want to do is when the user clicks on the span it changes the html after the label an adds an input box and submit button.
I think I need to do a this.document but not sure
Hi hope this might give you a small understanding of what to do when it comes to registering events. StackOverflow is about you learning how to do something, so we dont write the scripts for you, we are just trying to point you in the right direction of it.
http://jsfiddle.net/WKWFZ/2/
I would recommend you to import jQuery library, as done in the example, if possible. It makes the the world of javascript alot easier!
Documentation to look up:
http://api.jquery.com/insertAfter/
http://api.jquery.com/bind/
Look up some jQuery tutorials! there is alot of them out there.
I added a form which will hold the input
JavaScript:
function showInput()
{
document.getElementById('container').innerHTML += '<input type="text"/><input type="submit"/>';
}
HTML:
<div id="container">
<span class="spanright" onclick"showInput()">Update</span>
<label class="myinfo"><b>Business information:</b></label>
</div>
Summoner's answer is right, but I prefer using jquery (it's loaded on almost every page I work with):
HTML:
<div id="container">
<span class="spanright">Update</span>
<label class="container"><b>Business information:</b></label>
</div>​
Javascript:
​$(".spanright").click(function(){
$("#container").append('<br /><input type="text"/><input type="submit"/>');
$(".spanright").unbind('click');
})​​;​
This way, the click event will work once, as it is what you probably intended.
Try this in jquery flavor --
$(document).ready(function(){
$(".spanright").click(function(){
$(".myinfo").css("color","red");
});
});
Check fiddle --
http://jsfiddle.net/swapnesh/yHRND/

Is it okay to use custom tags instead of <p> tag?

I have some HTML with CSS and one instance where I used a custom HTML tag instead of <p> it shows up and my CSS picks up the tag and another where it fails to show the text. If I replace
<title>Layout Controls</title> with <p>Layout Controls</p> it shows up.
I've put a demo up on JSfiddle. THe JS works in my browser and Coda2 but not in JS fiddle. I'm probably doing something wrong as far as fiddle is concerned too if anyone can point out what that is to me.
If there are any best-practice comments people care to make that's fine by me too, here to learn.
<body>
<div class="input_group_box">
<title>Layout Controls</title><br />
<sub-title>X-Position</sub-title><br />
<input id="/layout/1/slider" class="slider" type="range" value="0" min="-1" max="1" step="0.001" onclick="bind('/layout/1', 'slider', parseInt(this.value*1000)/1000)" />
<input id="/layout/1/number" class="number-box" type="number" value="0" min="-1" max="1" step="0.01" onclick="bind('/layout/1', 'number', parseFloat(this.value))" /><br />
</div>
</body>
Anybody no why my Javascript isn't binding the two inputs in the demo. Could it be I need to change the JSFiddle load settings I'm in the dark a bit with that.
There are several problems with using custom tags, see e.g. Using custom HTML Tags. They would make coding a little easier, but mostly it’s not a good idea. Use classes instead, such as <div class=sub-title>...</div>. But if something is a heading, consider using heading markup for it, like h2 and h3. For form fields, you could use legend inside a fieldset, too.
The title element is a different case, since it has always been defined in HTML and has a special role and processing. It is allowed in the head part only. If you put it inside the body, the effect depends on the browser.
<title> is MTML5 tag, not custom tag.
Try this on it's CSS. It will be fine:
title {
font-size: 16px;
font-family: HelveticaNeue-Bold, sans-serif;
display: inline;
}
I suspect <title> tag is reserved for page title and you should not be using it for any other purpose...

Categories