Should I write an implementation of a custom element whithin <body>? - javascript

Like the below code, the implementation of a custom element is imported.
And is naked, which means, the imported document has no body and head.
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="import" href="html/demo-element.html">
</head>
<body>
<demo-element>hello world</demo-element>
</body>
</html>
demo-element.html
<template>
<style type="text/css">
div {
background-color: #F2CEE5;
padding: 10px;
}
</style>
<div>
<content></content>
</div>
</template>
<script type="text/javascript">
(function() {
var thisDoc = document.currentScript.ownerDocument;
var proto = Object.create(HTMLElement.prototype, {
createdCallback: {
value: function() {
var t = thisDoc.querySelector('template');
var clone = document.importNode(t.content, true);
this.createShadowRoot().appendChild(clone);
}
}
});
var element = document.registerElement('demo-element', {
prototype: proto
});
})();
</script>
I want you see the below which is the result which chrome dev tool shows.
The imported document has head and body and the implementation is in head somehow.
I want to know if this is common or I should write head and body in demo-element.html and put the implementation in the body.

Related

Setting color theme in Google Sheets sidebar via cell value

I would like the Google Sheets sidebar to open with a color set in cell Sheet1:A1. My current code works (I suspect there may be a more efficient way to do this), but the CSS steps through each theme in root until it lands on the correct theme.
For example, if A1 is set to 'Orange', calling the sidebar will load with the body first as 'Default' and then switch to 'Orange'. Is there a way to load the correct root theme on the initial page load instead of stepping through the themes in root?
Google Apps Script
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu("Sidebar")
.addItem("Show sidebar", "showSidebar")
.addToUi();
}
function showSidebar() {
var htmlWidget = HtmlService.createTemplateFromFile('Test').evaluate()
.setTitle("Theme Test");
SpreadsheetApp.getUi().showSidebar(htmlWidget);
}
function getColorTheme() {
colorTheme = SpreadsheetApp.getActive().getRange("Sheet1!A1").getDisplayValue();
return colorTheme;
}
HTML for Sidebar
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
:root,
:root.Default {
--bg-color: #45818e;
}
:root.Orange {
--bg-color: #e69138;
}
body {
background-color: var(--bg-color);
}
</style>
<script>
function setTheme(colorTheme) {
document.documentElement.className = colorTheme;
}
</script>
</head>
<body>
<p>Hello world</p>
<script>
google.script.run.withSuccessHandler(setTheme).getColorTheme();
</script>
</body>
</html>
From your situation, how about the following patterns?
Pattern 1:
In this pattern, HTML is modified using Google Apps Script and the modified HTML is used with HtmlService.createHtmlOutput().
Google Apps Script side:
function showSidebar() {
var colorTheme = SpreadsheetApp.getActive().getRange("Sheet1!A1").getDisplayValue();
var html = HtmlService.createHtmlOutputFromFile('Test').getContent().replace("{{colorTheme}}", colorTheme);
var htmlWidget = HtmlService.createHtmlOutput(html).setTitle("Theme Test");
SpreadsheetApp.getUi().showSidebar(htmlWidget);
}
HTML side:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
:root,
:root.Default {
--bg-color: #45818e;
}
:root.Orange {
--bg-color: #e69138;
}
body {
background-color: var(--bg-color);
}
</style>
<script>
document.documentElement.className = "{{colorTheme}}";
</script>
</head>
<body>
<p>Hello world</p>
</body>
</html>
Pattern 2:
In this pattern, HTML is modified using HTMl template and the modified HTML is used with HtmlService.createHtmlOutput().
Google Apps Script side:
function ashowSidebar() {
var colorTheme = SpreadsheetApp.getActive().getRange("Sheet1!A1").getDisplayValue();
var htmlWidget = HtmlService.createTemplateFromFile('Test')
htmlWidget.colorTheme = colorTheme;
SpreadsheetApp.getUi().showSidebar(htmlWidget.evaluate().setTitle("Theme Test"));
}
HTML side:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
:root,
:root.Default {
--bg-color: #45818e;
}
:root.Orange {
--bg-color: #e69138;
}
body {
background-color: var(--bg-color);
}
</style>
<script>
document.documentElement.className = "<?= colorTheme ?>";
</script>
</head>
<body>
<p>Hello world</p>
</body>
</html>
Note:
From the recent benchmark of the HTML template, it seems that in the current stage, the process cost of evaluate() is a bit high. Ref So, I proposed the above 2 patterns with and without an HTML template.
In this case, <html class="{{colorTheme}}"> and <html class="<?= colorTheme ?>"> might be able to be used instead of Javascript. But, I'm not sure about your actual situation. So, in this answer, Javascript is used as a sample modification.
References:
createHtmlOutput(html)
HTML Service: Templated HTML
createTemplateFromFile(filename)

Why isn't importNode executing when everything is fine?

I want to use HTML import so I created two files.
File1:
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
File2:
<!DOCTYPE html>
<html>
<head>
<link rel='import' href='test.html' id='LINK'>
<script>
var LINK = document.getElementById('LINK');
var test = LINK.import;
var content = document.importNode(test.content, true);
document.body.appendChild(content);
</script>
</head>
<body>
</body>
</html>
I should see a yellow square when I execute File2 but instead I'm getting this error:
Uncaught TypeError: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'.
at Import.html:8
When I log the "test" variable to the console, I am getting the document that contains File1 so it's fine there. I just don't get what the error is supposed to mean and why it's not working.
When you write:
var content = document.importNode(test.content, true);
...you suppose that test is a <template> element.
So in the document you import, you should have a <template> element.
test.html:
<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<template><div></div></template>
</body>
</html>
In the main file, use querySelector() (or another selector function) to get the template:
var LINK = document.getElementById('LINK');
var test = LINK.import.querySelector('template');
var content = document.importNode(test.content, true);
...

Canvas Shadow DOM and Web Components

I am trying to make use of web components, templates and shadow DOM to create a canvas element. The problem is i cannot get the contex inside the prototype or I get this error when creating the shadow: HierarchyRequestError: Failed to execute 'createShadowRoot' on 'Element': Author-created shadow roots are disabled for this element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="import" href="mycanvas.html">
</head>
<body>
<canvas is="my-canvas"></canvas>
</body>
</html>
<template id="mytemplate">
<style>
p {color:green;}
span {text-decoration: underline;}
canvas {background-color: #f00;
width:300px;}
</style>
</template>
<script>
(function() {
var myPrototype= Object.create(HTMLElement.prototype);
var myDocument=document.currentScript.ownerDocument;
myPrototype.createdCallback=function() {
var shadow= this.createShadowRoot();
var template=myDocument.querySelector("#mytemplate");
var clone= document.importNode(template.content, true);
shadow.appendChild(clone);
} //end prototype
var myCanvas= document.registerElement('my-canvas', {
prototype: myPrototype,
extends:'canvas'
});
}());
</script>
regardless of how I try to get the html canvas element ( with
getElementsByTagName or anythig else) it says getContext is not a
function
Try substituting HTMLCanvasElement.prototype for HTMLElement.prototype when defining myPrototype

how to get the cssText of external style?

I have tried hours to get the results, but failed, below, I will post all I have done, hope I can get some tips, BTW,Thanks.
from the error message, yeah It's cssRules is null, surely error!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="index.css">
<title>css style</title>
<style type="text/css">
#demo {
font-size: 10px; /*first css rule */
}
p {
border: 1px solid green; /*second one*/
}
</style>
</head>
<body>
<div id="demo" style="color: red;">
<p>how to access of document's css!</p>
</div>
</body>
external css
#demo {
font-weight: 900;
}
p {
padding: 20px;
}
Javascript
<script>
/*1,to get the inline style, this maybe the most easy one*/
var cssInline = document.getElementById('demo').style;
var cssInText = cssInline.cssText, cssColor = cssInline.color;
console.log(cssInText, cssColor);
/*2.a to get the style in head*/
var cssInHeada = document.getElementById('demo');
// using the computed css of inline
var cssHeadText = getComputedStyle(cssInHeada, null);
console.log(cssHeadText);
// 2.b to get the style directly
var cssInHeadb = document.getElementsByTagName('style')[0];
console.log(cssInHeadb.textContent);
// 2.c or like this
var cssInHeadc = document.styleSheets[1];
console.log(cssInHeadc.cssRules[0].cssText); //per rule
/*3, but I cant get the extenal style*/
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
</script>
Thank your guys!
I suspect your JavaScript is running before the stylesheet is loaded. Try this:
document.addEventListener('DOMContentLoaded', function () {
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
}, false);
Or if you happen to be using jQuery, this is more universal:
$('document').ready(function(){
var cssExtenal = document.styleSheets[0];
console.log(cssExtenal.cssRules[0].cssText);
});
Update: another possibility is that you're using Chrome and either loading the CSS cross-domain or using the file:// protocol. This appears to be a known issue and is not considered a bug.

error in javascript toggle class

I have this code for toggling class using pure JavaScript that I found online and it is not working when I am using it in an offline website
my code is -
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
any help would be appreciated
Move the script below the div you are looking for in the source code.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
</body>
</html>
You cannot manipulate the dom before it is ready.
So either load the script that adds the handler at the end of the body tag, or use the DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
Try adding the event handler after the div has rendered - for example in the onload event
Live Demo
<!DOCTYPE html>
<html>
<head>
<script>
function classToggle() {
if (!this.classList) return; // no support
this.classList.toggle('class1');
this.classList.toggle('class2');
}
window.onload=function() {
document.getElementById('div').onclick=classToggle;
}
</script>
<style type="text/css">
.class1 {
color: #f00;
}
.class2 {
color: #00f;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
</body>
</html>
codepen demo
//vanilla js -- toggle active class
// el = object containing the elements to toggle active class and the parent element
var el = {
one: document.getElementById('one'),
two: document.getElementById('two'),
three: document.getElementById('three'),
hold: document.getElementById('hold')
};
// func = object containing the logic
var func = {
toggleActive: function(ele) {
ele = event.target;
var hold = el.hold.children;
var huh = el.hold.children.length;
var hasActive = ele.classList.contains('active');
for (i = 0; i < huh; i++) {
if (hold[i].classList.contains('active')) {
hold[i].classList.remove('active');
}
}
if (!hasActive) {
ele.classList.add('active');
}
}
};
//add listeners when the window loads
window.onload = function() {
var holdLen = el.hold.children.length;
for (i = 0; i < holdLen; i++) {
el.hold.children[i].addEventListener("click", func.toggleActive);
}
};

Categories

Resources