I am trying to create my own custom HTML elements where a user can interact with the text within that element. For Example, I created an element where anything between those tags will have a pointer as a mouse cursor and when double clicked, something happens. EG:
<objdc>Double click me!</objdc>
However, this is my code and it is not working:
$(document).ready(function() {
var ObjDblClk = $('objdc');
ObjDblClk.css({ cursor: 'pointer' });
ObjDblClk.dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var word = $.trim(range.toString());
if(word != '') {
//Do Something
}
range.collapse();
e.stopPropagation();
});
});
}
Any suggestions?
The problem you have is related with the fact you are not using the collapse method right. It expects a node as parameter and an offset.
So... to fix that exact behavior you posted you would need to do something like:
ObjDblClk.dblclick(function(e) {
var range = window.getSelection() || document.getSelection() || document.selection.createRange();
var word = $.trim(range.toString());
if(word != '') {
//Do Something
}
range.collapse(ObjDblClk[0], 0);
e.stopPropagation();
});
BUT (and this is important): That will do absolutely nothing for your custom selection (especially since is on double click witch affects selection). So you can just remove that line completely and try another solution.
Also: You should read the comments. The guys are right. Unless you are working on some reall strange inhouse thing there may be better aproaches.
Fiddle here (added an alert so you see the function is called - don't forget to select something before double clicking): https://jsfiddle.net/713ndkm0/1/
To create a custom tag like that, you have to be aware of certain things:
Not all browsers will understand your custom tag as a DOM object. IE is a notable example.
Your new custom tag should have a hyphen in it, like obj-dc (more info).
If you want to use it in IE, you have to declare it up-front, as:
document.createElement('obj-dc');
Here is a link to creating new HTML tags for Chrome, in the new way, and here is a link for the older API. As you can see, even the same browser cannot operate with custom tags consistently.
I have working on this problem for a couple weeks off and on. What I am trying to do is have placeholders to show users where they can type. When they do type, I want the placeholder to disappear, but reappear again when the div is empty.
Every thing I have found has to do with cross-browser placeholder support for inputs and textareas, and trying to apply the code for them to my issue results in failure.
I am using h1s for titles and standard divs for descriptions.
My code looks like this:
HTML
<div class="page-desc" contenteditable="true" data-placeholder="Write your description here."></div>
jQuery
var placeholder = '<span class="placeholder">Write your title here</span>';
$(this).html(placeholder);
I have more jQuery code, but it sucks. I am currently using keyup to hide the placeholder, and that's obviously not working. Can someone help me out?
I am totally open to using vanilla JavaScript as well.
You can have something like this:
$('#xdiv').html($('#xdiv').data('placeholder'));
$('#xdiv').keydown(function() {
if ($(this).html() == $(this).data('placeholder')) {
$('#xdiv').html('');
}
})
$('#xdiv').keyup(function() {
if ($(this).html() == '') {
$('#xdiv').html($('#xdiv').data('placeholder'));
}
})
Initially it sets DIV's HTML to placeholder text. Then when user begins to type (on keydown) it checks if DIV still has the placeholder text and if so - removes it. And since user can delete all the data - it checks (on keyup) if DIV is empty, and if so - restores placeholder's text.
Demo: http://jsfiddle.net/bP7RF/
there's a way to do it in css (modern browser only)
.pageDesc:empty:after {content : "Write your description here.";}
Javascript solution (not as pretty, but more cross-browser):
$("#in").keyup(function(){
if(!$(this).html()){
$(this).html($(this).attr('data-placeholder'));
$(this).attr('showing-placeholder',true);
}
});
$("#in").keydown(function(){
if($(this).attr('showing-placeholder')){
$(this).html('');
$(this).attr('showing-placeholder','');
}
});
Working Example: JSFiddle;
Why not use the Blur and Focus event handlers from jQuery and check the Text value of the Div?
Code for quick look:
$('[contenteditable="true"]').blur(function() {
var text = $.trim($(this).text());
var ph = $('<span/>',{ 'class':"placeholder"})
.text($(this).data('placeholder')||'');
if (text == '') {
$(this).html(ph);
}
}).focus(function() {
if ($(this).children('.placeholder').length > 0) {
$(this).html('<span> </span>');
}
});
Fiddle for example: http://jsfiddle.net/qvvVr/1/
Why can't you use the placeholder attribute of the input element.
It seems to do exactly what you want and it's very well supported
(http://caniuse.com/input-placeholder).
Sorry if I have missed something.
For example, i have a div which users can type into it. i would like to place shortcuts so when the user inputs the word pi. The output would be the symbol π. Or if the user inputs sqrt then they would get this symbol inf then the output would be ∞. and even when the tab button is clicked to indent a couple of lines. I have not seen a web app that does this yet so any help would be appreciated.
There's some extensive key tracking + field updating you can do to accomplish this, or you can get a jQuery plugin that already does something similar (if not exactly) and modify it to accomplish the same task.
This might be what you are looking for though:
http://code.google.com/p/js-hotkeys/wiki/about
You could simply use a replace. See JSFiddle demo here
$('.test').keydown(function (event) {
if ($('.test').val().contains("pi")) {
var newVal = $('.test').val().replace("pi", "π");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
else if ($('.test').val().contains("inf")) {
var newVal = $('.test').val().replace("inf", "∞");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
});
In this sample I am using an input. You can change that to div
I am working on a service which will allow editing of text. To aid the user in the process, I'd like to allow the user to set a text field to overwrite mode, as is possible in Word, etc. How can the behaviour of an HTML text box be changed to overwrite instead of insert text as the user types?
For example, if the textbox had the text:
This is a trst.
The user could click between the r and the t, type a single e and the text would then be
This is a test.
with the cursor between the e and the s. I'm currently using jQuery, so methods using either that or pure javascript would be preferred. I would accept any reasonable solution, however.
That's a bit of crazy but it seems to work somehow :)
Based on this answer and this answer this piece of code was created.
$("textarea").on("keypress", function(e) {
var key = String.fromCharCode(e.which || e.charCode || e.keyCode);
if (/[A-Za-z0-9 ]/.test(key)) {
var text = this.innerHTML;
var caret = getCaret(this);
var output = text.substring(0, caret);
this.innerHTML = output + key + text.substring(caret + 1);
setCaretPosition(this, caret + 1);
return false;
}
return true;
});
DEMO: http://jsfiddle.net/aHSzC/
It works but now I have no time to fix a small bug I found.
If you press Backspace it seems to behave like a forward eraser.
Anyway, here is the code that can be improved. Feel free to edit my answer and do whatever you like.
Input elements have an onkeypress attribute. You could make it call a function that gets rid of the character after the cursor. jQuery has a Caret extension that you could use to find out where the caret is.
I'm creating a <select> replacement using jQuery to replace it with divs and links.
Now I want to filter it when I start to type something with the new select open.
Like Google Translate does on the language selector.
Do you have any advice how do i proceed?
I started something with:
$(document).bind('keypress', function(event) {
//...
});
But I capture only single keys, not the whole typed string.
Important:
I don't have an <input /> to detect the keypress or keyup events on it
I prefer not to create this <input /> since I want to use only <div>'s and <a>'s on the "new select"
Lately I'll need to navigate on the open select with arrow keys + enter to select the option with my keyboard
You could achieve this by 'listening' about what is pressed on the window, and then detecting the particular letter/string pressed, search through items list and if you find it change its css properties or add a new 'selected' class i.e. (demo => http://jsfiddle.net/steweb/mC6tn/ ..try pressing whatever :) and added after something found press left or right btns, or enter) :
JS: (supposing that each element you want to find something into and select it has class 'elem')
var whatYouAreSearching = $('<div class="searching-string"></div>'); //just to see what string you're typing
$(document.body).append(whatYouAreSearching);
function search(what){
what = what.toLowerCase();
$('.elem').removeClass('selected'); //reset everything
$.each($('.elem'),function(index,el){
if($(el).html().toLowerCase().indexOf(what) > -1){
$(el).addClass('selected');
return false; //found, 'break' the each loop
}
});
}
var letterPressed = [];
var timeOutResetLetters = null;
$(window).keypress(function(e) {
clearTimeout(timeOutResetLetters); //clear timeout, important!
timeOutResetLetters = setTimeout(function(){ //if 500 ms of inactivity, reset array of letters pressed and searching string
letterPressed = [];
whatYouAreSearching.html('');
},500);
letterPressed.push(String.fromCharCode(e.keyCode)); //look at the comment, thanks Niclas Sahlin
whatYouAreSearching.html(letterPressed.join('')); //show string
search(letterPressed.join('')); //and search string by 'joining' characters array
});
EDIT added left/right/enter keys handling
$(window).keydown(function(e){ //left right handling
var currSelected = $('.elem.selected');
if(e.keyCode == "37"){ //left, select prev
if(currSelected.prev() && currSelected.prev().hasClass('elem')){
currSelected.prev().addClass('selected');
currSelected.removeClass('selected');
}
}else if(e.keyCode == "39"){ //right, select next
if(currSelected.next() && currSelected.next().hasClass('elem')){
currSelected.next().addClass('selected');
currSelected.removeClass('selected');
}
}else if(e.keyCode == "13"){ //enter
$('.entered').remove();
$(document.body).append(currSelected.clone().addClass('entered'));
}
});
You can try using jQuery UI's autocomplete
How to do what you asked
Each time the keypress event is triggered on the document, keep a record of the character that was typed, either in a variable (accessible from the global scope or in a closure) or in an element on the page (you may choose to use display: hidden; if you don't want this to be visible to the user).
Then, do a pass over the elements in your dropdown and hide those that don't contain/start with the string you've built from individual keystrokes.
What's actually recommended
Use an input element to contain the user's typed keystrokes, and let the user see the element.
Why?
Because it's an interaction behavior users are already familiar with. If you don't use an input element, you open several new questions that are already solved with an input element:
How does the user know that they can type to filter the list? Input elements are a clear declaration to the user: "You should type here!"
How does the user know what string is going to be filtered on when they press more than one key? When I quickly type 'hu' in that Google Translate interface, 'Hungarian' is selected, as I would expect. However, what happens when I type it slowly? If it's slow enough, 'Hatian Creole' is selected, and then 'Ukranian'.
What if I mistype something and want to start over? Is there a button to press to clear it out? How long do I need to wait for the filter to clear on its own?
You could certainly create a new interface element that solves all of these problems, and if that's your goal, go for it, but there are preexisting standards for these sorts of things.
For one, that previously-mentioned autocomplete widget is really handy, and really flexible.
you can try something like this:
var _interval;
$("#textarea/field_id").bind('keypress', function(event) {
clearTimeout(_interval);
_interval = setTimeout(onTimeout, 1000);
});
function onTimeout(){
var words = $("#textarea/field_id").val().split(' ');//do what you want with the string in the field
}
This will capture the entire string onTimeout. Play with the timeout a little bit to get it nice and clean!
What about this:
var word='';
$(document).bind('keypress', function(event) {
//UPDATE word ACCORDING TO THE CHAR, LIKE:
if (event.charCode >=48 && event.charCode <=57) {
.... ....
.... ....
}
//OR
switch(event.charCode) {
.... ....
.... ....
}
});
I created my own version of a <select> with <div> tags, check it out here.. If i understand you correctly, this is what you want..
http://jsfiddle.net/myTPC/
It also supports backspace (atleast in firefox).
What I've tried to do is:
1) get the keypressed (only 0-9, a-z and space) and save this inside a div
2) created a LI list (you can use a div with a-elements, that's fine aswell)
3) find LI-items with the text that's being saved
4) add up/right down/left arrows to get next/previous item in the list
For now it keeps all items in the list, you can hide them aswell if you want. It's just an illustration.
// EDIT:
Here's a starters setup: http://www.pendemo.nl/keyinputtest.html
In firefox the body doesn't get automatically selected which causes that you need to click the body/webpage again before a second input is being detected. In Chrome it detects keys pressed after eachother.
// EDIT2:
Working in firefox. Text is now saved inside a div (you can type a string you want and see it being placed in the body).
// EDIT3:
Added an UL list with some items. typing some text will filter this list with items matching the typed string.
// EDIT4:
Only a-z and space are being used to search. Still looking for a way on how to find the backspace key. Since Chrome is adding 'history.go-1' by default. Firefox however does notice the backspace key. event.preventDefault() is not changing anything in Chrome.
// EDIT5:
Added up+right arrow to select next and left+down array to select previous item.
// EDIT6:
Upon using the enter key, the current value is alert. Ofcourse the scripts stops after the alert. But as you can see the value is available for you.
Here's the code I came up with so far:
var typed_string = '';
$(document).ready(function() { $('#typedtext').select(); });
$(document).bind('keypress', function(event) {
event.preventDefault();
if((event.which > 47 && event.which < 58) || (event.which > 96 && event.which < 123) || event.which == 32) {
typed_string = typed_string + String.fromCharCode(event.which);
$('#typedtext').html(typed_string);
$('#testlist li').css('background-color', '#ffffff');
$('#testlist li:contains('+typed_string+')').css('background-color', 'green').first().addClass('selected').css('background-color', 'red');
$('#typedtext').select();
}
if(event.which == 13) {
alert('Selected item: ' + $('.selected').html());
$('#typedtext').select();
}
});
$(document).keyup(function(event) {
event.preventDefault();
if(event.which == 38 || event.which == 37) {
$('#testlist li').css('background-color', '#ffffff');
$('#testlist li:contains('+typed_string+')').css('background-color', 'green');
$('.selected').removeClass('selected').prev().css('background-color', 'red').addClass('selected');
}
if(event.which == 39 || event.which == 40) {
$('#testlist li').css('background-color', '#ffffff');
$('#testlist li:contains('+typed_string+')').css('background-color', 'green');
$('.selected').removeClass('selected').next().css('background-color', 'red').addClass('selected');
}
});
function clearInput() {
typed_string = '';
}
And I'm using this HTML:
Press any key to save text.<br /><br />
<div id="typedtext" style="border: 1px solid #09F; padding: 5px;"></div>
<br /><br />
Let's test to filter some items from the li. (use up/down or left/right keys to select next item)
<ul id="testlist">
<li>item</li>
<li>test</li>
<li>more test</li>
<li>another item</li>
<li>test item</li>
<li>more item</li>
<li>foo</li>
<li>foo bar</li>
<li>bar</li>
<li>more foo</li>
</ul>
I think it's easy enough for you to change the HTML code to fit your needs.
What's the reason you don't want to use an input, is it just so if JS isn't available you can graceful fall back to the select? If so this might do what you want, I've used the select as a basis and taken the values from there although I have ended up putting an input in there.
Following on from Neal's answer, I think autocomplete is fairly similar to what you need, but if you want to display the results differently I've got a second approach in the same example that displays the filtered results.
Full example version here:
http://jsfiddle.net/R7APm/9/
Here's the JS from it:
$opts = $('option', '#myselect');
//Grab the text from the select (could use option values instead with .val()
var values = [];
$.each($opts, function(i, opt) {
values.push($(opt).text());
});
$div = $('<div/>');
//Autocomplete version
$input = $('<input/>').autocomplete({
source: values
});
//Filter in div version
$wordlist = $('<div id="wordlist"/>');
$wordlist.text(values.join(", "));
$input.keyup(function() {
matches = $.grep(values, function(el, i) {
if (el.toLowerCase().indexOf($input.val().toLowerCase()) >= 0) {
return true;
} else {
return false;
}
});
$wordlist.text(matches.join(", "));
});
//Add new elements to wrapper div
$div.append($input);
$div.append($wordlist);
//Replace select with wrapper div
$('#replaceme').replaceWith($div);
$input.focus();
If you don't want to use a hidden dropdown (which i still strongly advise) i suggest following:
Make the DIV focusable
This works thanks to the "tabindex" workaround found at
http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex
Capture only the keystrokes on your custom dropdown, NOT just all on the whole document. First, it's unusual behavior. Second, how would you deal with more than 1 custom dropdown?
Store the filter string via jQuery's data container
Check out the full working demo with a simple language dropdown at http://jsfiddle.net/aWE8b/
The demo contains:
Custom Dropdown
Supported keys:
Backspace
Enter
Escape
Left, Up
Right, Down
2 Modes:
Filter: remove unmatched items
Select: highlight first matched item