fyngyrz
fyngyrz

Reputation: 2658

oninput="function()" works with textarea, but not div, in Safari. Why?

Testing in, and for use with, Safari 11.0.1 under OSX 10.12.6;

I would like to use oninput="function()" in a <div> with contenteditable="true" set. Bare-bones test page case works with <textarea>, but not <div>. Here's the test code; change script first var load getElementById parameter to dpagecontentx from tpagecontentx to see it work with textarea and not work with div.

<HTML>
  <HEAD>
    <SCRIPT>
      function onCharInput()
      {
        var conpagechars = document.getElementById("tpagecontentx").value;
        var conpagecharcount = conpagechars.length.toString();
        document.getElementById("pccount").innerHTML = conpagecharcount;
      }
    </SCRIPT>
    <title>Editor</title>
  </HEAD>
  <BODY>
    <center>
      <div id="dpagecontentx" oninput="onCharInput()" name="dpagecontent" contenteditable="true" style="font-family: Courier; padding: .5em; text-align: left; border-color: #000000; border-width: 1px; border-style: solid; width: 60em; height: 24em;"></div>
      <TEXTAREA id="tpagecontentx" oninput="onCharInput()" NAME="tpagecontent" ROWS=10 COLS=80>foo</TEXTAREA>
    </center>
    <p>
      Content Size: <span id="pccount"></span>
    </p>
  </BODY>
</HTML> 

Upvotes: 1

Views: 6828

Answers (1)

YouneL
YouneL

Reputation: 8371

The oninput event is only fired when the value of an <input>, <select>, or <textarea> element is changed, For a <div> tag You can use keyup event to detect changes, Here is working example:

function onCharInput(e)
{
  // here I use tagName property to get the element content
  // according to its type
  if (e.target.tagName === 'DIV') {
    var conpagechars = document.getElementById("dpagecontentx").innerText; 
  } else {
    var conpagechars = document.getElementById("tpagecontentx").value;
  }

  var conpagecharcount = conpagechars.length.toString();
  document.getElementById("pccount").innerHTML = conpagecharcount;
}
<center>
<div id="dpagecontentx" onkeyup="onCharInput(event)" name="dpagecontent" contenteditable="true" style="font-family: Courier; padding: .5em; text-align: left; border-color: #000000; border-width: 1px; border-style: solid; width: 60em; height: 24em;"></div>
<TEXTAREA id="tpagecontentx" oninput="onCharInput(event)" NAME="tpagecontent" ROWS=10 COLS=80>foo</TEXTAREA>
</center>
<p>
Content Size: <span id="pccount"></span>
</p>

Upvotes: 1

Related Questions