Siem Peters Siem Peters - 9 months ago 74
CSS Question

A lot of span tags inside a contenteditable div

I want to make a textfield with a lot of words that are editable. Each word should be able to have a different color. I also need to do some other css changes on each word e.g. change font per word.

I have the list of words in a javascript array. I make a lot of spans inside the a contenteditable div. I loop through the array and assign each words to the each span with javascript.

However, when I have a lot of words, the scroll in the div gets very slow. Does anyone know how to fix this? Or have another solution?

HTML:

<div contenteditable id="editor">

</div>


JS:

var text = ['one', 'two', 'three'];


function printwords(){
for (var i = 0, len = text.length; i < len; i++){
var dataSpan = document.createElement('span');
document.getElementById('editor').appendChild(dataSpan);
dataSpan.setAttribute("id", i+"id");
$('#'+i+'id').css('background', 'rgba(255, 0, 0, 0.5)');
document.getElementById(i+'id').innerHTML = text[i]+' ';
};
};
printwords();

Answer Source

There are some problems with your actual code:

  • You are creating a spanelement, appending it to the editable div then give it more attributes, or editing it's attributes, what will be better is to create the element, change its attributes then at the end apend it to the DOM.
  • You are creating the element, giving it an id, then you will get it from the DOM with this given id twice with $('#'+i+'id') and document.getElementById(), you are overkilling your page here, you already have the element in a variable why would you try to get it by id again, just use your dataSpan variable.

So your actual code is working but with huge number of items in the array, it will give bad performance, that's the scroll in the div gets very slow.

This is how should be your code:

function printwords() {
  for (var i = 0, len = text.length; i < len; i++) { 
    var dataSpan = document.createElement('span');
    dataSpan.setAttribute("id", i + "id");
    dataSpan.style.background = 'rgba(255, 0, 0, 0.5)';
    dataSpan.innerHTML = text[i] + ' ';

    document.getElementById('editor').appendChild(dataSpan);
  };
};

Demo:

var text = ['one', 'two', 'three'];


function printwords() {
  for (var i = 0, len = text.length; i < len; i++) { 
    var dataSpan = document.createElement('span');
    dataSpan.setAttribute("id", i + "id");
    dataSpan.style.background = 'rgba(255, 0, 0, 0.5)';
    dataSpan.innerHTML = text[i] + ' ';

    document.getElementById('editor').appendChild(dataSpan);
  };
};
printwords();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div contenteditable id="editor">

</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download