Reputation: 63
I am creating a text editor using HTML, CSS, and JS. I've got most of the functions worked out, and even though it is deprecated, I've been using document.execCommand()
to stylize text content in a contenteditable
div. I have a hotbar at the top of the screen that has all the buttons to change the font, change the size, bold, italic, underline etc. Similarly to google docs, I would like the top bar to update its values to match those of whatever text is selected. I've got a function that grabs the HTML of a text selection thanks to another post on this site:
function getHTMLOfSelection () {
var range;
if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
return range.htmlText;
}
else if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
return div.innerHTML;
}
else {
return '';
}
}
else {
return '';
}
}
But I don't know how to grab the css of the whole thing. For instance, if half the selection is Arial font, and the other is Serif. I want it to pick the first. But I don't even know how to start with getting the CSS. Here is what I have so far:
function updateControlBar() {
selection = getHTMLOfSelection();
if (typeof selection != "undefined") {
// Get the selection's font and update the font menu to show it.
document.getElementById('font-button').value = selection.fontFamily;
document.getElementById('font-button').style.fontFamily = selection.fontFamily;
console.log(selection.fontFamily);
} else {
console.log("No selection, cannot update control bar values.");
}
}
Thanks for the help!
Upvotes: 1
Views: 164
Reputation: 9077
Looks like you can now use getComputedStyle().
Try the following:
var bEl = document.querySelector("body");
getComputedStyle(bEl);
You'll see :
I ran it on this page (via console) and I saw over 400 css properties listed.
CSS2Properties(486)
Upvotes: 1