How to handle/ subscribe an event raised inner html in angular? - javascript

[enter link description here][1]First of all - let me make it clear that I am very new to angular. Please pardon me if you find something stupid.
Objective - I am trying to make a custom spell checker. In that I want the ziggy redline when ever a user will press a space bar(in case the spelling is wrong). Here in the program I just used one word just to make sure red underline is coming.
Problem - after hitting the space redline appears but the cursor goes back at the starting of the word.
My Approach - Wheneever there is a spelling mistake i put that word in a span. Now, in that span I will continously raise event on every Keyup to check the spelling, reason being is that if the user puts space between the word thats inside a span I will create two spans removing the already existing span.
[http://plnkr.co/edit/W1qMrTHxksBShYsJeXdl?p=preview]

Related

Text Highlighting - Content Editable

I've been experimenting with contenteditable fields in javascript. As you can probably guess, I'm trying to build a WYSIWYG editor. Piecing together answers I found on Stack Overflow, I managed to build this test case. The test case's job is to manually and programmatically highlight text and embolden it. There is just one small problem. If you click the "bold" button once, a substring is highlighted and subsequently made bold. However, if you click it again, it prompts an error:
"Error: Failed to execute 'setStart' on 'Range': There is no child at offset 12.
at Error (native)
at HTMLInputElement.<anonymous> (http://run.jsbin.io/runner:15:13)
at HTMLDocument.oa (http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js:18:373)
at HTMLDocument.c.event.handle (http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js:55:307)
at HTMLDocument.j.handle.o (http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js:49:363)"
After the first button press, the text field representing the WYSIWYG editor's content contains the following:
Some text he<span style="font-weight: bold;">re for y</span>ou to bold
Upon testing (by outputting the first child's length), my hypothesis is that it's trying to highlight only the first part - "Some text he." Further testing, including commenting out the statement to embolden the selection, confirmed this, I believe. In fact, when this is commented out the editor works well.
I searched on Google and Stack Exchange, yet partially due to my ignorance as to why this is happening I could find nothing.
My question is therefore - why is this error appearing, and what can I do to avoid it and reach my goal of programmatically highlighting and embolding this text?
Referring to your linked demo code, you're setting the range with this code:
range.setStart(mainDiv.firstChild, 12);
range.setEnd(mainDiv.firstChild, 20);
But mainDiv.firstChild is the first text node of main div. On initial run that text node is
Some text here for you to bold
After the first run that text node gets broken into three pieces: 1 before the bold, one inside the bold, and one after.
Some text he<span style="font-weight: bold;">re for y</span>ou to bold
So your mainDiv.firstChild becomes
Some text he
For that reason the call to range.setEnd(mainDiv.firstChild, 20) is out of range.
To avoid this, don't hard-code your calls to setRange. Instead get your ranges directly from user selection (a very common case) or after inspecting the actual DOM just prior to making the call.

Autofill Text box on a Web Page (Javascript/VBScript)

I really need to know how I can autofill text boxes on a web page.
What I really want to achieve is the following:
1) Go to http://show.websudoku.com
2) Replace all the empty cells with a 0 (zero).
Is that possible?
To fill the empty spaces of the Sudoku grid at http://show.websudoku.com with zero's, here is some JavaScript to do that. It is formatted for use as a "Bookmarklet":
javascript:(function(){var x,k,f,j,r;x=document.forms;for(k=0;k<x.length;++k){f=x[k];for(j=0;j<f.length;++j){r=(f[j].className.toLowerCase()+f[j].type.toLowerCase()+f[j].value);if(r=="d0text"){f[j].value="0";}else if(r=="d0text0"){f[j].value="";}}}})();
The setup:
Create a new Bookmark/Favorite. For now, the URL for the favorite can be anything. An easy way to do this is to drag ANY link/url from the browser address bar, or any web-page link, to the "Favorites Bar" or to the Bookmarks/Favorites sidebar.
Select the new favorite, and rename it to any name you like.
Copy the JavaScript code from above to the clipboard. It must remain as 1 continuous single line, and it must begin with "javascript:(" and end with ")();"
Edit the properties of the new favorite.
Remove the "URL" that is currently in the favorite and replace it by pasting in the JavaScript code from above, into the "URL" text field for the favorite, then save the changes.
To use the bookmarklet:
From the browser, navigate to http://show.websudoku.com as you normally would.
Click the new favorite (Bookmarklet) that you just edited.
All empty spaces in the Sudoku grid will be filled with 0's. Click the new favorite (Bookmarklet) again, and the 0's will be removed leaving empty spaces once again.
Here is what the Javascript code looks like expanded, with indents:
javascript:(function(){
var x,k,f,j,r;
x=document.forms;
for(k=0;k<x.length;++k){
f=x[k];
for(j=0;j<f.length;++j){
r=(f[j].className.toLowerCase()+f[j].type.toLowerCase()+f[j].value);
if(r=="d0text"){
f[j].value="0";
}
else if(r=="d0text0"){
f[j].value="";
}
}
}
}
)();
* Spoiler alert *
In case you want to "cheat", the JavaScript here will "solve" the Sudoku:
javascript:(function(){var x,k,f,j,ecl,etl,en,ev,s,e,c,d,dl,dr,n;x=document.forms;for(k=0;k<x.length;++k){f=x[k];for(j=0;j<f.length;++j){e=f[j];r=(e.name.toLowerCase());if(r=="cheat"){c=e.value;break;}}for(j=0;j<f.length;++j){e=f[j];ecl=e.className.toLowerCase();etl=e.type.toLowerCase();en=e.name;ev=e.value;if(etl=="text"){if(ecl=="d0"){dr=en.substr(en.length-1,1);dl=en.substr(en.length-2,1);d=(((Number(dr)-1)*9)+Number(dl))-1;n=c.substr(d,1);if(ev.length==0){e.value=n;}else{e.value="";}}}}}})();
Setup and use is the same as described above.
While it's not much fun to solve it like that (OK, maybe it's a little fun the first couple times), and definitely not challenging, if you are in a real-real-real hurry, you can solve it in 1 click.
Note: I have only tested these 2 bookmarklets with IE9.

Determine visible characters to be highlighted using html source

I'm using TinyMCE to let users edit and format text, output is html code.
The html is then sent to the server and is pushed to other clients that can follow the edit progress on a webpage, the html is inserted into a div so users can see the format but they are not able to edit.
Now I want the cursor position and any selection the user makes in the editor to show up on the readonly page using highlight(background color) if selected or inserting an empty span with a black border between characters to imitate the cursor position.
I made an attempt using
editor.tinymce().selection.getRng()
which gives me the start and end position of what the user sees(formatting characters are not counted)
Then I traversed the DOM and counted the characters in every text element wrapping the ones selected with a highlight span. This resulted in messy code but worked pretty well until I hit a non ascii or encoded character in the textblock.
Example html
<p>abc <b>de</b>fg</p>
looks like this to the user
abc defg
Say user selected character c to d (selection covers c, a blank, first half of the bold tag and d),
tinymce will return range start:2 end:5
but the actual characters behind would be start:5 end:16.
Just wrapping the text from char 5 to 16 in a highlight span will result in bad html.
Checking for words starting with & and ending with ; and adding number of positions will turn into a mess. There has to be a simpler way
How do I calculate how many "visible" characters a set of html character will turn into?
Or maybe you would attack the problem in another way
Thanks
PS 1
I've looked into the various jquery highlight plugins but they seem to highlight based on a search string. Those does not work in the case user selects one character and that character exists several times, they will then highlight all occurences.
I've tackled this problem in my Rangy library: the TextRange module concerns itself with the text the user sees. It sounds like you need the selectCharacters() and toCharacterRange() methods of Rangy's Range objects.

Dynamically growing an array of text inputs (HTML/JavaScript)

I'm creating a data entry app for some in-house stuff.
My team needs to enter info about "items" which can have many "categories" and vice versa.
I need a quick way to let them enter an arbitrary amount of categories.
Here's my idea:
On the item entry page, I'll have it so that initially there's one text input for "categories" and if it's tabbed out of while it's empty, the input field is deleted (unless it's the only one) and focus skips to the next field. If it's not empty when it's tabbed out of and if it's the last input field in the array, then an additional "category" text input will be added and focused.
This way people can enter an arbitrary amount of categories really quickly, without taking their hands off the keyboard, just by typing and hitting tab. Then hitting tab twice to denote the end of the list.
First of all, what do you think of this interface? Is there a better way to do it?
Second of all, is there a jQuery (or something) plugin to do this? I've searched but can't find one. I searched scriptaculous/prototype and mootools too, with no luck.
I would obviously rather use something tried and tested than roll my own.
Any and all advice appreciated
First I'll try to address the problems commented on nickf solution.
To set the focus on the newly created input $copy.find(":text").focus(); will not work. The jQuery focus method only triggers the event, but does not call the underlying focus method.
You can set the focus with setTimeout(function(){$copy.find(":text").get(0).focus()}, 10); but:
setTimeout is needed in firefox or strange things will happen with the blinking cursor.
IE7 needs another input to focus when tabbing. I haven't found the way to set the focus on an input if the focus goes to the address bar. I suppose this will not be a problem because you will need at least a submit button.
To control shift-tab I've been trying to track the focused element, in order to skip the blurHandler when the focused element is a previous input, but the resulting code is really ugly so I'll post this and look for a better solution.
And last, you're asking what we think of this UI, and I think that a comma separated list of categories is easier to code an to fill in. :-)
it's actually not too difficult to implement that, even with vanilla JS (ie: no jQuery, prototype, etc), but everything is easier with jQuery, so I'll have a go at it using that:
Assuming a structure like this:
<form id="myForm">
<div class="inputRow">
<input type="text" name="myInput[]" />
</div>
<div class="inputRow">
<input type="text" name="myInput[]" />
</div>
...
</form>
Here's the JS
$('#myForm :text').blur(onBlurHandler);
function onBlurHandler() {
$row = $(this).parent();
if ($row
.nextAll(":has(:text)") // all following divs with a text element
.length == 0 // but there aren't any, we're on the last one
) {
if ($.trim($row.find(":text").val())) { // the text box isn't empty
$copy = $row.clone(true);
$copy
.find(":text") // get the new text box,
.val('') // remove any text in it
.blur(onBlurHandler) // and add the event handler (is this necessary?)
;
$copy.insertAfter($row);
} else if ($row.prev(':has(:text)').length) { // the text box is empty, and this one isn't the first row
$row.remove(); // get rid of the row.
}
}
}
Response to comments:
thanks for the answer! i've tried it but it doesn't seem to work as intended. i'm on mac firefox. if i tab off the last field, it adds the new one but focuses the address bar. i tried adding: $copy.find(":text").focus(); after the insertAfter line, but it doesn't change anything. any ideas?
also if i shift-tab the blurhandler doesn't know i'm going in the opposite direction. is there any way around that?
Hmm, I hadn't thought about that. What you could try doing is to put an element after all your text fields which can take focus (like a textbox which is rendered off-screen, eg: margin-left: -10000px). Add an onfocus handler onto that to see if the last row is empty, and if it is, then it would have been added just then by the onBlurHandler function, so pass the focus back to the last row. If the last row isn't empty, then pass the focus onto the next element (your submit button, probably). If there are issues with the last row not existing in the DOM yet, then put the above into a timeout.
(If this actually works) this should let your users tab backwards and forwards without hassle.

TinyMCE Plugin building

I am working on modifying an existing spell check plugin for TinyMCE.
This is what is supposed to happen:
1. User hits "space" and the spell check runs.
2. If the word is spelled wrong the word gets wrapped with a span and gets a red underline
what I find happening is that when the user hits space bar the word does get spell checked but the cursor pops back to the end of the word just typed (instead of to where the space is) (you can see this in action at http://mail.solidhouse.com/webmail2/test.html)
here is my pseudcode:
var b = this.editor.selection.getBookmark();
//for each node
node.nodeValue.replace(r5, '$1$2');
this.editor.selection.moveToBookmark(b);
what I am suspecting is that moveToBookmark keeps the cursor within the element but I have no idea what to do to remedy this.
(I have tried incrementing b.start and b.end but that did not work)
I know this is hard to explain. Any thoughts on this are greatly appreciated.
try incrementing the bookmark start/end by 2 instead of 1 if you haven't already. since the underline adds a tag around the mispelled words, that's an additional 2 places that need to be accounted for in the bookmark: 1 for each side of the span.
Can you get yourself out of the element by grabbing its parent?
this.parentNode.moveToBookmark(b);
Or something like that.

Categories