Detect if browser supports contentEditable? - javascript

There's this question, but the solution posted is browser sniffing, which I'm trying to avoid.
I need to make my website compatible with the iPad and perhaps newer Androids. I've been using an old version of the FCKEditor (now CK Editor) for my WYSIWYG editors, but that doesn't work on mobile, so I want to swap it out for a simple textarea with something like markdown, if it's not supported.
Supposedly it won't work because mobile devices tend not to support this contentEditable property, which means the on-screen keyboard won't pop up when you click on it.
How can I detect if the browser supports contentEditable? It's been suggested that I just check the div in question with something like mydiv.contentElement === undefined or something like that, but the div (if it's using one) is all built into the FCK Editor and buried somewhere in an iframe.
Isn't there another way to detect if a browser supports contentEditable in general?
Just tried this:
var contentEditableSupport = typeof $('<div contenteditable="true">')[0].contentEditable !== 'undefined';
Says "true" on my iPad...... I don't think it should.
Edit: It's returning "string" because all attributes are strings.... it's just reading the attribute. How else am I supposed to do this?

You could create an anonymous editable div, check it for contentEditable, then remove the div.

Here is the test I use and is also used in Modernizr. It will give false positives in iOS 4 (and possibly earlier) but unfortunately it's impossible to detect in those environments.
var contentEditableSupport = "contentEditable" in document.documentElement;

I was able to accomplish this by checking the default value of the contentEditable property rather than the presence or type. The W3 spec indicates that the missing value default for contentEditable is "inherit", but in older browsers (e.g. Android/Gingerbread) the default value is "false". Thanks to fudgey for the comment on the OP that pointed me in the right direction!
This test works for me:
var contentEditableSupport = $('<div/>')[0].contentEditable == 'inherit';

Check for execCommand
if (document.execCommand) {
... browser supports contentEditable
} else {
... browser doesn't support contentEditable
}

To check if any propery exits for a element. You can do this
var element = document.createElement('__ELEMENT__');
if ('__PROPERTY__' in element ) {
// property supported in the browser
}
or
if ('__PROPERTY__' in document.createElement('__ELEMENT__') ) {
// property supported in the browser
}
The below link contains it all.
https://github.com/Modernizr/Modernizr/issues/570
http://diveintohtml5.info/everything.html#contenteditable

Related

onChange is not working IE8

I am dynamically creating a text area, based on the number of each user, comment for each user.
i am using the below code to do the same, it works fine in all the browser except IE8.
$(template1).find('textarea').attr({"id":'selfasgn'+aud.ASGN_ID,"onchange":'captureSelfComments('+aud.ASGN_ID+')'})
note that $(template1) is clone of one of the element in node.
template1 = reviewTemplate.clone(true);
function captureSelfComments(p_asgnid){
alert('caling captureSelfComments');
}
I tried below code, but its getting called when this element gets constructed or appened to the DOM. so i removed it.
$(template1).find('textarea').live('change',captureSelfComments(aud.ASGN_ID))
am I doing anything wrong here ?
For IE, try propertychange() as described here since IE may not always support the change event.
var lowIE = /msie (6|7|8)/gi.test(window.navigator.userAgent);
$(template1).find('textarea').live(lowIE ? 'propertychange' : 'change',captureSelfComments(aud.ASGN_ID));
Generally, it is not a good idea to do user agent sniffing but we are talking about IE... which is basically also not a good idea, generally :)

javascript event not working with IE7

When I select any option in list then it should print its value in textbox(all html).
I tried
stafflist.setAttribute("onchange", "javacript:document.getElementById('id_17_enrolpassword').value = this.value;");
Its working in IE8+ and all modern browsers but not in IE7.
Also tried
stafflist.addEventListener('onchange',"javacript:document.getElementById('id_17_enrolpassword').value = this.value;",false);
So what changes I should do here?
IE only fires the onchange event when the element loses focus - if you were to click outside the element or tab to a different element it should fire then.
You can get around this by using a different even, for example onkeypress
1) the javascript: label is only needed if the first script on the page is vbscript.
2) does this work better?
document.getElementById('stafflist').onchange=function(){
document.getElementById('id_17_enrolpassword').value = this.value;
}
?
do it this way -
stafflist.onchange = function(){
document.getElementById('id_17_enrolpassword').value= this.value;
}
I know this doesn't truly answer the question at hand, but, can't you use something like jQuery to code these sort of even handlings?
The code is a bit more readable (IMHO), and you don't have to deal this these cross-browser scripting issues yourself.

get textarea value using javascript in opera

I am trying to get the value of a textarea, to check if it's empty, using Javascript and it doesn't work in Opera. In IE, FF and Chrome it works fine, but in Opera 11 and 10 it reports the value to be the empty string, even if it has text.
Here's my code:
if (document.getElementById('mytextareaid').value.replace(/(^\s+|\s+$)/, '') == '') {
alert('empty textarea');
}
Using document.getElementById('mytextareaid').innerHTML instead, doesn't work, either. What am I missing?
Replace with this and try
if (document.getElementById('mytextareaid').innerHTML.replace(/(^\s+|\s+$)/, '') == '') {
alert('empty textarea');
}
Thank you all for your help. It turns out that it works with a simple page that only has a textarea, but in my particular HTML document it didn't. I finally found a workaround here:
JQuery val() does not work for textarea in Opera
I don't know what exactly caused the strange behavior, but I do know that the piece of
Quoting myself from
JQuery val() does not work for textarea in Opera :
You may have come across a very obscure bug referred to in a blog post on the Opera sitepatching blog ( http://my.opera.com/sitepatching/blog/facebook-and-some-core-patches ) as "PATCH-287, Hack to make script see typed value in TEXTAREA on blog.ebuddy.com. Opera fails to read correct value from a previously hidden textarea".
I'm a little bit reluctant to recomment workarounds without seeing the full code.
However, when I was looking at this I noticed that setting textarea.contentEditable to something seemed to let me read the value afterwards..it's a weird hack though, and it might cause problems for other browsers.

'innerText' works in IE, but not in Firefox

I have some JavaScript code that works in IE containing the following:
myElement.innerText = "foo";
However, it seems that the 'innerText' property does not work in Firefox. Is there some Firefox equivalent? Or is there a more generic, cross browser property that can be used?
Update: I wrote a blog post detailing all the differences much better.
Firefox uses W3C standard Node::textContent, but its behavior differs "slightly" from that of MSHTML's proprietary innerText (copied by Opera as well, some time ago, among dozens of other MSHTML features).
First of all, textContent whitespace representation is different from innerText one. Second, and more importantly, textContent includes all of SCRIPT tag contents, whereas innerText doesn't.
Just to make things more entertaining, Opera - besides implementing standard textContent - decided to also add MSHTML's innerText but changed it to act as textContent - i.e. including SCRIPT contents (in fact, textContent and innerText in Opera seem to produce identical results, probably being just aliased to each other).
textContent is part of Node interface, whereas innerText is part of HTMLElement. This, for example, means that you can "retrieve" textContent but not innerText from text nodes:
var el = document.createElement('p');
var textNode = document.createTextNode('x');
el.textContent; // ""
el.innerText; // ""
textNode.textContent; // "x"
textNode.innerText; // undefined
Finally, Safari 2.x also has buggy innerText implementation. In Safari, innerText functions properly only if an element is
neither hidden (via style.display == "none") nor orphaned from the document. Otherwise, innerText results in an empty string.
I was playing with textContent abstraction (to work around these deficiencies), but it turned out to be rather complex.
You best bet is to first define your exact requirements and follow from there. It is often possible to simply strip tags off of innerHTML of an element, rather than deal with all of the possible textContent/innerText deviations.
Another possibility, of course, is to walk the DOM tree and collect text nodes recursively.
Firefox uses the W3C-compliant textContent property.
I'd guess Safari and Opera also support this property.
If you only need to set text content and not retrieve, here's a trivial DOM version you can use on any browser; it doesn't require either the IE innerText extension or the DOM Level 3 Core textContent property.
function setTextContent(element, text) {
while (element.firstChild!==null)
element.removeChild(element.firstChild); // remove all existing content
element.appendChild(document.createTextNode(text));
}
jQuery provides a .text() method that can be used in any browser. For example:
$('#myElement').text("Foo");
As per Prakash K's answer Firefox does not support the innerText property. So you can simply test whether the user agent supports this property and proceed accordingly as below:
function changeText(elem, changeVal) {
if (typeof elem.textContent !== "undefined") {
elem.textContent = changeVal;
} else {
elem.innerText = changeVal;
}
}
A really simple line of Javascript can get the "non-taggy" text in all main browsers...
var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);
Note that the Element::innerText property will not contain the text which has been hidden by CSS style "display:none" in Google Chrome (as well it will drop the content that has been masked by other CSS technics (including font-size:0, color:transparent, and a few other similar effects that cause the text not to be rendered in any visible way).
Other CSS properties are also considered :
First the "display:" style of inner elements is parsed to determine if it delimits a block content (such as "display:block" which is the default of HTML block elements in the browser's builtin stylesheet, and whose behavior as not been overriden by your own CSS style); if so a newline will be inserted in the value of the innerText property. This won't happen with the textContent property.
The CSS properties that generate inline contents will also be considered : for example the inline element <br \> that generates an inline newline will also generate an newline in the value of innerText.
The "display:inline" style causes no newline either in textContent or innerText.
The "display:table" style generates newlines around the table and between table rows, but"display:table-cell" will generate a tabulation character.
The "position:absolute" property (used with display:block or display:inline, it does not matter) will also cause a line break to be inserted.
Some browsers will also include a single space separation between spans
But Element::textContent will still contain ALL contents of inner text elements independantly of the applied CSS even if they are invisible. And no extra newlines or whitespaces will be generated in textContent, which just ignores all styles and the structure and inline/block or positioned types of inner elements.
A copy/paste operation using mouse selection will discard the hidden text in the plain-text format that is put in the clipboard, so it won't contain everything in the textContent, but only what is within innerText (after whitespace/newline generation as above).
Both properties are then supported in Google Chrome, but their content may then be different. Older browsers still included in innetText everything like what textContent now contains (but their behavior in relation with then generation of whitespaces/newlines was inconsistant).
jQuery will solve these inconsistencies between browsers using the ".text()" method added to the parsed elements it returns via a $() query. Internally, it solves the difficulties by looking into the HTML DOM, working only with the "node" level. So it will return something looking more like the standard textContent.
The caveat is that that this jQuery method will not insert any extra spaces or line breaks that may be visible on screen caused by subelements (like <br />) of the content.
If you design some scripts for accessibility and your stylesheet is parsed for non-aural rendering, such as plugins used to communicate with a Braille reader, this tool should use the textContent if it must include the specific punctuation signs that are added in spans styled with "display:none" and that are typically included in pages (for example for superscripts/subscripts), otherwise the innerText will be very confusive on the Braille reader.
Texts hidden by CSS tricks are now typically ignored by major search engines (that will also parse the CSS of your HTML pages, and will also ignore texts that are not in contrasting colors on the background) using an HTML/CSS parser and the DOM property "innerText" exactly like in modern visual browsers (at least this invisible content will not be indexed so hidden text cannot be used as a trick to force the inclusion of some keywords in the page to check its content) ; but this hidden text will be stil displayed in the result page (if the page was still qualified from the index to be included in results), using the "textContent" property instead of the full HTML to strip the extra styles and scripts.
IF you assign some plain-text in any one of these two properties, this will overwrite the inner markup and styles applied to it (only the assigned element will keep its type, attributes and styles), so both properties will then contain the same content. However, some browsers will now no longer honor the write to innerText, and will only let you overwrite the textContent property (you cannot insert HTML markup when writing to these properties, as HTML special characters will be properly encoded using numeric character references to appear literally, if you then read the innerHTML property after the assignment of innerText or textContent.
myElement.innerText = myElement.textContent = "foo";
Edit (thanks to Mark Amery for the comment below): Only do it this way if you know beyond a reasonable doubt that no code will be relying on checking the existence of these properties, like (for example) jQuery does. But if you are using jQuery, you would probably just use the "text" function and do $('#myElement').text('foo') as some other answers show.
innerText has been added to Firefox and should be available in the FF45 release: https://bugzilla.mozilla.org/show_bug.cgi?id=264412
A draft spec has been written and is expected to be incorporated into the HTML living standard in the future: http://rocallahan.github.io/innerText-spec/, https://github.com/whatwg/html/issues/465
Note that currently the Firefox, Chrome and IE implementations are all incompatible. Going forward, we can probably expect Firefox, Chrome and Edge to converge while old IE remains incompatible.
See also: https://github.com/whatwg/compat/issues/5
This has been my experience with innerText, textContent, innerHTML, and value:
// elem.innerText = changeVal; // works on ie but not on ff or ch
// elem.setAttribute("innerText", changeVal); // works on ie but not ff or ch
// elem.textContent = changeVal; // works on ie but not ff or ch
// elem.setAttribute("textContent", changeVal); // does not work on ie ff or ch
// elem.innerHTML = changeVal; // ie causes error - doesn't work in ff or ch
// elem.setAttribute("innerHTML", changeVal); //ie causes error doesn't work in ff or ch
elem.value = changeVal; // works in ie and ff -- see note 2 on ch
// elem.setAttribute("value", changeVal); // ie works; see note 1 on ff and note 2 on ch
ie = internet explorer, ff = firefox, ch = google chrome.
note 1: ff works until after value is deleted with backspace - see note by Ray Vega above.
note 2: works somewhat in chrome - after update it is unchanged then you click away and click back into the field and the value appears.
The best of the lot is elem.value = changeVal; which I did not comment out above.
As in 2016 from Firefox v45, innerText works on firefox, take a look at its support: http://caniuse.com/#search=innerText
If you want it to work on previous versions of Firefox, you can use textContent, which has better support on Firefox but worse on older IE versions: http://caniuse.com/#search=textContent
What about something like this?
//$elem is the jQuery object passed along.
var $currentText = $elem.context.firstChild.data.toUpperCase();
** I needed to make mine uppercase.
Just reposting from comments under the original post. innerHTML works in all browsers. Thanks stefita.
myElement.innerHTML = "foo";
found this here:
<!--[if lte IE 8]>
<script type="text/javascript">
if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
!Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get)
(function() {
var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
Object.defineProperty(Element.prototype, "textContent",
{ // It won't work if you just drop in innerText.get
// and innerText.set or the whole descriptor.
get : function() {
return innerText.get.call(this)
},
set : function(x) {
return innerText.set.call(this, x)
}
}
);
})();
</script>
<![endif]-->
It's also possible to emulate innerText behavior in other browsers:
if (((typeof window.HTMLElement) !== "undefined") && ((typeof HTMLElement.prototype.__defineGetter__) !== "undefined")) {
HTMLElement.prototype.__defineGetter__("innerText", function () {
if (this.textContent) {
return this.textContent;
} else {
var r = this.ownerDocument.createRange();
r.selectNodeContents(this);
return r.toString();
}
});
HTMLElement.prototype.__defineSetter__("innerText", function (str) {
if (this.textContent) {
this.textContent = str;
} else {
this.innerHTML = str.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<').replace(/\n/g, "<br />\n");
}
});
}

Adding an input field to the dom and focusing it in IE

I am trying to make a div, that when you click it turns into an input box, and focuses it. I am using prototype to achieve this. This works in both Chrome and Firefox, but not in IE. IE refuses to focus the newly added input field, even if I set a 1 second timeout.
Basically the code works like this:
var viewElement = new Element("div").update("text");
var editElement = new Element("input", {"type":"text"});
root.update(viewElement);
// pseudo shortcut for the sake of information:
viewElementOnClick = function(event) {
root.update(editElement);
editElement.focus();
}
The above example is a shortened version of the actual code, the actual code works fine except the focus bit in IE.
Are there limitations on the focus function in IE? Do I need to place the input in a form?
My guess is that IE hasn't updated the DOM yet when you make the call to focus(). Sometimes browsers will wait until a script has finished executing before updating the DOM.
I would try doing the update, then doing
setTimeout("setFocus", 0);
function setFocus()
{
editElement.focus();
}
Your other option would be to have both items present in the DOM at all times and just swap the style.display on them depending on what you need hidden/shown at a given time.
What version IE? What's your DocType set to? is it strict, standards or quirks mode? Any javascript errors appearing (check the status bar bottom left for a little yellow warning sign) ? Enable error announcing for all errors via Tools > Options > Advanced.
Oisin
The question is already answered by 17 of 26. I just want to point out, that Prototype has native mechanism for this: Function.defer()

Categories

Resources