define word boundaries for HTML5 spellcheck - javascript

I have some HTML in a contenteditable that looks like <span>hello wor</span><strong>ld</strong></span>. If I change it, so that world is misspelt, I would like to be able to get suggestions on this complete word. However, this is what actually happens:
The text is separated into two words, left clicking simply gives suggestions for one or the other.
Is there any recourse?

The implementation of “spelling checks” requested by using the spellcheck attribute (which the question is apparently about) is heavily browser-dependent, and the HTML5 spec intentionally leaves the issue open. Browsers may implement whatever checks they like, the way they like, and they do. You cannot change this in your code.
Although modern browsers generally have spelling checks of some kind at least for English, they differ in the treatment of cases like this, among other things. Firefox treats adjacent inline elements (with no whitespace between them) as constituting one word, but Chrome and IE do not. Moreover, browsers might not spellcheck initial content, only content as entered or edited by the user.
The only way to get consistent spelling checking is to implement it yourself: instead of using the spellcheck attribute (“HTML5 spellcheck”), you would need to have spelling checking routine and integrate it into your HTML document using JavaScript. People who have implemented such systems normally have the routine running server-side and make the HTML page communicate with it using Ajax.

Related

cross-browser way to get contenteditable's content

Different browsers generate the elements inside contenteditable differently. It's especially obvious when you have line breaks, or paste multi-line stuffs in.
In the old days with textarea, you can simply do $('textarea').val() to retrieve the content inside, and it's reliable and cross-browser compatible.
I wonder is there such universally-agreed method to retrieve content inside a contenteditble as well, such that it's striped off html tags, and lines are properly separated by \n. If not, how does Facebook messenger do it reliably? Do you need a complicated algorithm with browser detection?
One way to do it would be this:
var content = document.querySelector('[contenteditable]').textContent
The jury's still out on whether it's universally agreed upon because you would probably have to account for differences between browsers regarding newlines and what not.

What's the best method for creating a simple Rich-Text WYSIWYG editor?

I need to create a simple rich-text editor that saves its contents to an XML file using arbitrary markup to indicate special text styles (e.g: [b]...[/b] for bold and [i]...[/i] for italic). All the backend PHP stuff seems fairly straightforward, but the front-end WYSIWYG portion of the feature seems a bit more convoluted. I've been reticent to use one of the currently-available JavaScript-based WYSIWYG editors because the rich-text options I want to allow are so limited, and these applications are so fully-featured that it almost seems like more work to stip them down to the functions I need.
So, in setting out to create a bare-bones rich-text editor, I've encountered three approaches:
The first two approaches use the contentEditable or designMode properties to create an editable element, and the execCommand() method to apply new text styles to a selected range.
The first option uses a standard div element, executes all styling commands on that elements contents.
The second option uses the editible body of a window enclosed in an iframe, then passes any styling commands initiated from buttons in the parent document into its contentWindow to alter selected ranges in the contained body. This seems like several extra steps to accomplish the same effect as option one, but I suppose the isolation of the editable content in its own document has its advantages.
The third option uses a textarea overlaying a div, and uses the oninput JS event to update the background div's innerHTML to match the input textarea's value whenever it changes. Obviously, this requires some string finagling to to convert elements like newline characters in the textarea to <br/> in the div, but this would allow me to preserve the integrity of my [/] markup, while relegating the potentially-messy DOM manipulation to front-end display only.
I can see benefits and drawbacks for each method. the contentEditable solutions seem initially the simplest, but support for this features tends to vary across browsers, and each browser that DOES support it seems to manipulate the DOM differently when implementing execCommand(). As mentioned before, the textarea/div solution seems like the best way to preserve my arbitrary styling conventions, but the custom string-manipulation procedure to display rich text in the output div could get pretty hairy.
So, I submit to you my question: Given the development goals I've outlined, which method would you choose, and why? And of course, if there's another method I'm overlooking that might better serve my purpose, please enlighten me!
Thanks in advance!
Have you looked at http://php.net/manual/en/book.bbcode.php? This is your answer. If you are having doubts, then you are doing something wrong. :-)
Then use JS to track keyup event and simple AJAX to print preview of the input. Just like in stackoverflow.
NB It would be far more efficient to generate the preview using plain-js BBcode approach. However, do not overcomplicate stuff unless you necessary need it.
The problem with BBCode, Markdown, ... is that it's not that trivial for genpop. I suggest looking at widgEditor, it is by far the simplest WYSIWYG editor I've seen to date. It was developed some time ago, so I am not sure about compatibility, but it sure is an inspiration.
I would have included this only as a comment, since it does not directly answer your question, but I am fairly new to SA and could not find out how to do that. Sorry.

Why is it bad practice to use links with the javascript: "protocol"?

In the 1990s, there was a fashion to put Javascript code directly into <a> href attributes, like this:
Press me!
And then suddenly I stopped to see it. They were all replaced by things like:
Press me!
For a link whose sole purpose is to trigger Javascript code, and has no real href target, why is it encouraged to use the onclick property instead of the href property?
The execution context is different, to see this, try these links instead:
Press me! <!-- result: undefined -->
Press me! <!-- result: A -->
javascript: is executed in the global context, not as a method of the element, which is usually want you want. In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.
Also, it's just much cleaner, though I wouldn't use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:
$('a').click(function() { alert(this.tagName); });
Actually, both methods are considered obsolete. Developers are instead encouraged to separate all JavaScript in an external JS file in order to separate logic and code from genuine markup
http://www.alistapart.com/articles/behavioralseparation
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
The reason for this is that it creates code that is easier to maintain and debug, and it also promotes web standards and accessibility. Think of it like this: Looking at your example, what if you had hundreds of links like that on a page and needed to change out the alert behavior for some other function using external JS references, you'd only need to change a single event binding in one JS file as opposed to copying and pasting a bunch of code over and over again or doing a find-and-replace.
Couple of reasons:
Bad code practice:
The HREF tag is to indicate that there is a hyperlink reference to another location. By using the same tag for a javascript function which is not actually taking the user anywhere is bad programming practice.
SEO problems:
I think web crawlers use the HREF tag to crawl throughout the web site & link all the connected parts. By putting in javascript, we break this functionality.
Breaks accessibility:
I think some screen readers will not be able to execute the javascript & might not know how to deal with the javascript while they expect a hyperlink. User will expect to see a link in the browser status bar on hover of the link while they will see a string like: "javascript:" which might confuse them etc.
You are still in 1990's:
The mainstream advice is to have your javascript in a seperate file & not mingle with the HTML of the page as was done in 1990's.
HTH.
I open lots of links in new tabs - only to see javascript:void(0). So you annoy me, as well as yourself (because Google will see the same thing).
Another reason (also mentioned by others) is that different languages should be separated into different documents. Why? Well,
Mixed languages aren't well supported
by most IDEs and validators.
Embedding CSS and JS into HTML pages
(or anything else for that matter)
pretty much destroys opportunities to
have the embedded language checked for correctness
statically. Sometimes, the embedding language as well.
(A PHP or ASP document isn't valid HTML.)
You don't want syntax
errors or inconsistencies to show up
only at runtime.
Another reason is to have a cleaner separation between
the kinds of things you need to
specify: HTML for content, CSS for
layout, JS usually for more layout
and look-and-feel. These don't map
one to one: you usually want to apply
layout to whole categories of
content elements (hence CSS) and look and feel as well
(hence jQuery). They may be changed at different
times that the content elements are changed (in fact
the content is often generated on the fly) and by
different people. So it makes sense to keep them in
separate documents as well.
Using the javascript: protocol affects accessibility, and also hurts how SEO friendly your page is.
Take note that HTML stands for Hypter Text something something... Hyper Text denotes text with links and references in it, which is what an anchor element <a> is used for.
When you use the javascript: 'protocol' you're misusing the anchor element. Since you're misusing the <a> element, things like the Google Bot and the Jaws Screen reader will have trouble 'understanding' your page, since they don't care much about your JS but care plenty about the Hyper Text ML, taking special note of the anchor hrefs.
It also affects the usability of your page when a user who does not have JavaScript enabled visits your page; you're breaking the expected functionality and behavior of links for those users. It will look like a link, but it won't act like a link because it uses the javascript protocol.
You might think "but how many people have JavaScript disabled nowadays?" but I like to phrase that idea more along the lines of "How many potential customers am I willing to turn away just because of a checkbox in their browser settings?"
It boils down to how href is an HTML attribute, and as such it belongs to your site's information, not its behavior. The JavaScript defines the behavior, but your never want it to interfere with the data/information. The epitome of this idea would be the external JavaScript file; not using onclick as an attribute, but instead as an event handler in your JavaScript file.
Short Answer: Inline Javascript is bad for the reasons that inline CSS is bad.
The worst problem is probably that it breaks expected functionality.
For example, as others has pointed out, open in new window/tab = dead link = annoyed/confused users.
I always try to use onclick instead, and add something to the URL-hash of the page to indicate the desired function to trigger and add a check at pageload to check the hash and trigger the function.
This way you get the same behavior for clicks, new tab/window and even bookmarked/sent links, and things don't get to wacky if JS is off.
In other words, something like this (very simplified):
For the link:
onclick = "doStuff()"
href = "#dostuff"
For the page:
onLoad = if(hash="dostuff") doStuff();
Also, as long as we're talking about deprecation and semantics, it's probably worth pointing out that '</a>' doesn't mean 'clickable' - it means 'anchor,' and implies a link to another page. So it would make sense to use that tag to switch to a different 'view' in your application, but not to perform a computation. The fact that you don't have a URL in your href attribute should be a sign that you shouldn't be using an anchor tag.
You can, alternately, assign a click event action to nearly any html element - maybe an <h1>, an <img>, or a <p> would be more appropriate? At any rate, as other people have mentioned, add another attribute (an 'id' perhaps) that javascript can use as a 'hook' (document.getElementById) to get to the element and assign an onclick. That way you can keep your content (HTML) presentation (CSS) and interactivity (JavaScript) separated. And the world won't end.
I typically have a landing page called "EnableJavascript.htm" that has a big message on it saying "Javascript must be enabled for this feature to work". And then I setup my anchor tags like this...
<a href="EnableJavascript.htm" onclick="funcName(); return false;">
This way, the anchor has a legitimate destination that will get overwritten by your Javascript functionality whenever possible. This will degrade gracefully. Although, now a days, I generally build web sites with complete functionality before I decide to sprinkle some Javascript into the mix (which all together eliminates the need for anchors like this).
Using onclick attribute directly in the markup is a whole other topic, but I would recommend an unobtrusive approach with a library like jQuery.
I think it has to do with what the user sees in the status bar. Typically applications should be built for failover in case javascript isn't enabled however this isn't always the case.
With all the spamming that is going on people are getting smarter and when an email looks 'phishy' more and more people are looking at the status bar to see where the link will actually take them.
Remember to add 'return false;' to the end of your link so the page doesn't jump to the top on the user (unless that's the behaviour you are looking for).

Create your own HTML Textfield with Javascript

I came across the following http://ckeditor.com/demo , and was wondering if anyone had a basic tutorial how to implement this (or perhaps what key search terms I should use)?
Is this just a heavily modified TextField, or have they somehow managed to create a completely new TextField from scratch?
I tried googling this many times, and I always get pages relating to customizing the built-in TextField with CSS etc.
A good place to start if you want to learn how richtext web editors work is to look into the contenteditable attribute and the document.execCommand method (the best editors use a lot more than this, but these are at the foundation). Over-simplified, an editor consists of a contenteditable block and ways to invoke document.execCommand on the text selection.
But, speaking as a person who has actually developed an editor of this kind, you might be better off using an existing one (CKEditor being a great one, in my opinion).
Edit: Note that contenteditable is a proprietary (Microsoft) property, but most (all?) browsers have implemented it now, and it will be in HTML5.
Edit 2: I want to try to clear up a few misconceptions.
A div or iframe isn't in itself editable, it requires the contenteditable attribute. The use of an iframe is typically a workaround for the fact that older Gecko browsers only supported an alternative editable property (designMode) that could only be applied to a whole document.
While some operations of advanced editors probably do employ innerHtml, this isn't the key to making an editor on the web.
It is not a textbox. It is a DIV that has lots of HTML injected to it with javascript.
The basic idea is that JavaScript uses the innerHtml property of the div and writes HTML to it.
This is a javascript implementation that replaces a input. It basically hides the input and uses it for storing and passing the data via POST.
The advanced textfields I have seen have all been iframe or div. The code behind them is quiet messy and not very accessible.
Proceed with caution!
You may want to consider WYSIWYM instead of WYSIWYG.

Does HTML and CSS needs to be valid before we apply JavaScript?

I was thinking about Web standards, and i was wondering if we need to have valid HTML and CSS before we apply JavaScript?
Can anyone enlighten me on the relation between valid HTML, CSS and JavaScript?
For instance, does invalid HTML and CSS prevent JavaScript from working correctly?
As much lip service as we pay to having valid HTML, browsers are extremely forgiving. The reasons for this are historical. There was (and still is) a lot of bad HTML in the beginning.
But you may get unpredictable differences between browsers with badly formed HTML. For example, different browsers may treat an unclosed tag differently.
All the markup causes to happen is to form a DOM (Document Object Model) in the browser based on how that browser interpreted it. CSS and Javascript are both applied to the DOM.
I disagree with the above responses: I have had very bad times hunting through apparent javascript bugs before I remembered to validate the page I was working on. As soon as I corrected the glaring errors, the scripts worked as intended.
The most obvious problem (not one I have experienced, because I already look for that): have two elements with the same id attribute, and try to make your script that depends on that to work as intended :)
While it may be true that the level of validation needed is somewhat low, when you are banging your head against the table because your website doesn't work and you don't know why, you'll remember this fondly.

Categories

Resources