I may be misunderstanding the purpose of .focus().
When I insert a table into a content editable element, I want to set the focus to the first cell of the table. By focus i mean the cursor will be in the first cell and the user can start typing directly into the cell without selecting it.
However I just can't seem to achieve this.
Also when I click off the table, on content inside the editable div only, I want to remove the ClassTwo from the table and can't get that right either
var iDoc;
iDoc = document.getElementById("MyEditor");
iDoc.focus();
function postedTableCap() {
alert("called");
$('.ClassTwo td:first').focus();
};
function insertTable(position, height, width, rows, columns, bkcolor, bcolor, bsiz, bstyle) {
var mybody = document.getElementById("MyEditor");
mytable = document.createElement("table");
mytablebody = document.createElement("tbody");
for (var r = 0; r < rows; r++) {
mycurrent_row = document.createElement("tr");
for (var c = 0; c < columns; c++) {
mycurrent_cell = document.createElement("td");
mycurrent_row.appendChild(mycurrent_cell);
}
mytablebody.appendChild(mycurrent_row);
}
mytable.appendChild(mytablebody);
mybody.appendChild(mytable);
mytable.className = "ClassOne";
mytable.classList.add("ClassTwo");
mytable.style.height = height + 'px';
mytable.style.width = width + 'px';
if (!(bsiz === undefined || bsiz === null)) {
mytable.style.borderColor = "#" + bcolor;
mytable.style.borderWidth = bsiz + 'px';
mytable.style.borderStyle = bstyle;
};
mytable.style.backgroundColor = '#' + bkcolor;
if (position == 1) {
//mytable.style.width = "auto"
mytable.style.marginLeft = "0px";
mytable.style.marginRight = "auto";
}
else if (position == 2) {
//mytable.style.width = "auto"
mytable.style.marginLeft = "auto";
mytable.style.marginRight = "auto";
}
else if (position == 3) {
//mytable.style.width = "auto"
mytable.style.marginLeft = "auto";
mytable.style.marginRight = "0px";
};
};
$("#MyBtn").click(function () {
var d1 = $.Deferred();
$.when(d1).then(function () {
$(".GSM-i-tbl-active").focus().blur();
$('.TableOptions').hide();
postedTableCap();
})
d1.resolve(insertTable(2, 200, 200, 3, 3, "#ff0000", "#0000FF", 1, "solid"));
});
table.ClassOne tr td{
border: 1px solid lightgrey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="MyBtn">
InsertTable
</button>
<div id="MyEditor" contenteditable="true" style="height:300px; width:300px; background-color:white;"></div>