Tag: HTML

Crafting Reusable HTML Templates

In our last article, we discussed the Web Components specifications (custom elements, shadow DOM, and HTML templates) at a high-level. In this article, and the three to follow, we will put these technologies to the test and examine them in greater detail and see how we can use them in production today. To do this, we will be building a custom modal dialog from the ground up to see how the various technologies fit together.

Article Series:

  1. An Introduction to Web Components
  2. Crafting Reusable HTML Templates (This post)
  3. Creating a Custom Element from Scratch (Coming soon!)
  4. Encapsulating Style and Structure with Shadow DOM (Coming soon!)
  5. Advanced Tooling for Web Components (Coming soon!)

HTML templates

One of the least recognized, but most powerful features of the Web Components specification is the <template> element. In the first article of this series, we defined the template element as, “user-defined templates in HTML that aren’t rendered until called upon.” In other words, a template is HTML that the browser ignores until told to do otherwise.

These templates then can be passed around and reused in a lot of interesting ways. For the purposes of this article, we will look at creating a template for a dialog that will eventually be used in a custom element.

Defining our template

As simple as it might sound, a <template> is an HTML element, so the most basic form of a template with content would be:

<template>   <h1>Hello world</h1> </template>

Running this in a browser would result in an empty screen as the browser doesn’t render the template element’s contents. This becomes incredibly powerful because it allows us to define content (or a content structure) and save it for later — instead of writing HTML in JavaScript.

In order to use the template, we will need JavaScript

const template = document.querySelector('template'); const node = document.importNode(template.content, true); document.body.appendChild(node);

The real magic happens in the document.importNode method. This function will create a copy of the template’s content and prepare it to be inserted into another document (or document fragment). The first argument to the function grabs the template’s content and the second argument tells the browser to do a deep copy of the element’s DOM subtree (i.e. all of its children).

We could have used the template.content directly, but in so doing we would have removed the content from the element and appended to the document’s body later. Any DOM node can only be connected in one location, so subsequent uses of the template’s content would result in an empty document fragment (essentially a null value) because the content had previously been moved. Using document.importNode allows us to reuse instances of the same template content in multiple locations.

That node is then appended into the document.body and rendered for the user. This ultimately allows us to do interesting things, like providing our users (or consumers of our programs) templates for creating content, similar to the following demo, which we covered in the first article:

See the Pen
Template example
by Caleb Williams (@calebdwilliams)
on CodePen.

In this example, we have provided two templates to render the same content — authors and books they’ve written. As the form changes, we choose to render the template associated with that value. Using that same technique will allow us eventually create a custom element that will consume a template to be defined at a later time.

The versatility of template

One of the interesting things about templates is that they can contain any HTML. That includes script and style elements. A very simple example would be a template that appends a button that alerts us when it is clicked.

<button id="click-me">Log click event</button>

Let’s style it up:

button {   all: unset;   background: tomato;   border: 0;   border-radius: 4px;   color: white;   font-family: Helvetica;   font-size: 1.5rem;   padding: .5rem 1rem; }

…and call it with a really simple script:

const button = document.getElementById('click-me'); button.addEventListener('click', event => alert(event));

Of course, we can put all of this together using HTML’s <style> and <script> tags directly in the template rather than in separate files:

<template id="template">   <script>     const button = document.getElementById('click-me');     button.addEventListener('click', event => alert(event));   </script>   <style>     #click-me {       all: unset;       background: tomato;       border: 0;       border-radius: 4px;       color: white;       font-family: Helvetica;       font-size: 1.5rem;       padding: .5rem 1rem;     }   </style>   <button id="click-me">Log click event</button> </template>

Once this element is appended to the DOM, we will have a new button with ID #click-me, a global CSS selector targeted to the button’s ID, and a simple event listener that will alert the element’s click event.

For our script, we simply append the content using document.importNode and we have a mostly-contained template of HTML that can be moved around from page to page.

See the Pen
Template with script and styles demo
by Caleb Williams (@calebdwilliams)
on CodePen.

Creating the template for our dialog

Getting back to our task of making a dialog element, we want to define our template’s content and styles.

<template id="one-dialog">   <script>     document.getElementById('launch-dialog').addEventListener('click', () => {       const wrapper = document.querySelector('.wrapper');       const closeButton = document.querySelector('button.close');       const wasFocused = document.activeElement;       wrapper.classList.add('open');       closeButton.focus();       closeButton.addEventListener('click', () => {         wrapper.classList.remove('open');         wasFocused.focus();       });     });   </script>   <style>     .wrapper {       opacity: 0;       transition: visibility 0s, opacity 0.25s ease-in;     }     .wrapper:not(.open) {       visibility: hidden;     }     .wrapper.open {       align-items: center;       display: flex;       justify-content: center;       height: 100vh;       position: fixed;         top: 0;         left: 0;         right: 0;         bottom: 0;       opacity: 1;       visibility: visible;     }     .overlay {       background: rgba(0, 0, 0, 0.8);       height: 100%;       position: fixed;         top: 0;         right: 0;         bottom: 0;         left: 0;       width: 100%;     }     .dialog {       background: #ffffff;       max-width: 600px;       padding: 1rem;       position: fixed;     }     button {       all: unset;       cursor: pointer;       font-size: 1.25rem;       position: absolute;         top: 1rem;         right: 1rem;     }     button:focus {       border: 2px solid blue;     }   </style>   <div class="wrapper">   <div class="overlay"></div>     <div class="dialog" role="dialog" aria-labelledby="title" aria-describedby="content">       <button class="close" aria-label="Close">&#x2716;&#xfe0f;</button>       <h1 id="title">Hello world</h1>       <div id="content" class="content">         <p>This is content in the body of our modal</p>       </div>     </div>   </div> </template>

This code will serve as the foundation for our dialog. Breaking it down briefly, we have a global close button, a heading and some content. We have also added in a bit of behavior to visually toggle our dialog (although it isn’t yet accessible). In our next article, we will put custom elements to use and create one of our own that consumes this template in real-time.

See the Pen
Dialog with template with script
by Caleb Williams (@calebdwilliams)
on CodePen.

Article Series:

  1. An Introduction to Web Components
  2. Crafting Reusable HTML Templates (This post)
  3. Creating a Custom Element from Scratch (Coming soon!)
  4. Encapsulating Style and Structure with Shadow DOM (Coming soon!)
  5. Advanced Tooling for Web Components (Coming soon!)

The post Crafting Reusable HTML Templates appeared first on CSS-Tricks.

CSS-Tricks

, , ,

Extracting Text from Content Using HTML Slot, HTML Template and Shadow DOM

Chapter names in books, quotes from a speech, keywords in an article, stats on a report — these are all types of content that could be helpful to isolate and turn into a high-level summary of what’s important.

For example, have you seen the way Business Insider provides an article’s key points before getting into the content?

That’s the sort of thing we’re going to do, but try to extract the high points directly from the article using HTML Slot, HTML Template and Shadow DOM.

These three titular specifications are typically used as part of Web Components — fully functioning custom element modules meant to be reused in webpages.

Now, what we aim to do, i.e. text extraction, doesn’t need custom elements, but it can make use of those three technologies.

There is a more rudimentary approach to do this. For example, we could extract text and show the extracted text on a page with some basic script without utilizing slot and template. So why use them if we can go with something more familiar?

The reason is that using these technologies permits us a preset markup code (also optionally, style or script) for our extracted text in HTML. We’ll see that as we proceed with this article.

Now, as a very watered-down definition of the technologies we’ll be using, I’d say:

  • A template is a set of markup that can be reused in a page.
  • A slot is a placeholder spot for a designated element from the page.
  • A shadow DOM is a DOM tree that doesn’t really exist on the page till we add it using script.

We’ll see them in a little more depth once we get into coding. For now, what we’re going to make is an article that follows with a list of key points from the text. And, you probably guessed it, those key points are extracted from the article text and compiled into the key points section.

See the Pen
Text Extraction with HTML Slot and HTML Template
by Preethi Sam (@rpsthecoder)
on CodePen.

The key points are displayed as a list with a design in between the points. So, let’s first create a template for that list and designate a place for the list to go.

<article><!-- Article content --></article>  <!-- Section where the extracted keypoints will be displayed --> <section id='keyPointsSection'>   <h2>Key Points:</h2>   <ul><!-- Extracted key points will go in here --></ul> </section>  <!-- Template for the key points list --> <template id='keyPointsTemplate'>   <li><slot name='keyPoints'></slot></li>   <li style="text-align: center;">&#x2919;&mdash;&#x291a;</li> </template>

What we’ve got is a semantic <section> with a <ul> where the list of key points will go. Then we have a <template> for the list items that has two <li> elements: one with a <slot> placeholder for the key points from the article and another with a centered design.

The layout is arbitrary. What’s important is placing a <slot> where the extracted key points will go. Whatever’s inside the <template> will not be rendered on the page until we add it to the page using script.

Further, the markup inside <template> can be styled using inline styles, or CSS enclosed by <style>:

<template id='keyPointsTemplate'>     <li><slot name='keyPoints'></slot></li>     <li style="text-align: center;">&#x2919;&mdash;&#x291a;</li>     <style>         li{/* Some style */}     </style> </template>

The fun part! Let’s pick the key points from the article. Notice the value of the name attribute for the <slot> inside the <template> (keyPoints) because we’ll need that.

<article>   <h1>Bears</h1>   <p>Bears are carnivoran mammals of the family Ursidae. <span><span slot='keyPoints'>They are classified as caniforms, or doglike carnivorans</span></span>. Although only eight species of bears <!-- more content --> and partially in the Southern Hemisphere. <span><span slot='keyPoints'>Bears are found on the continents of North America, South America, Europe, and Asia</span></span>.<!-- more content --></p>   <p>While the polar bear is mostly carnivorous, <!-- more content -->. Bears use shelters, such as caves and logs, as their dens; <span><span slot='keyPoints'>Most species occupy their dens during the winter for a long period of hibernation</span></span>, up to 100 days.</p>   <!-- More paragraphs -->  </article>

The key points are wrapped in a <span> carrying a slot attribute value (“keyPoints“) matching the name of the <slot> placeholder inside the <template>.

Notice, too, that I’ve added another outer <span> wrapping the key points.

The reason is that slot names are usually unique and are not repeated, because one <slot> matches one element using one slot name. If there’re more than one element with the same slot name, the <slot> placeholder will be replaced by all those elements consecutively, ending in the last element being the final content at the placeholder.

So, if we matched that one single <slot> inside the <template> against all of the <span> elements with the same slot attribute value (our key points) in a paragraph or the whole article, we’d end up with only the last key point present in the paragraph or the article in place of the <slot>.

That’s not what we need. We need to show all the key points. So, we’re wrapping the key points with an outer <span> to match each of those individual key points separately with the <slot>. This is much more obvious by looking at the script, so let’s do that.

const keyPointsTemplate = document.querySelector('#keyPointsTemplate').content; const keyPointsSection = document.querySelector('#keyPointsSection > ul'); /* Loop through elements with 'slot' attribute */ document.querySelectorAll('[slot]').forEach((slot)=>{   let span = slot.parentNode.cloneNode(true);   span.attachShadow({  mode: 'closed' }).appendChild(keyPointsTemplate.cloneNode(true));   keyPointsSection.appendChild(span); });

First, we loop through every <span> with a slot attribute and get a copy of its parent (the outer <span>). Note that we could also loop through the outer <span> directly if we’d like, by giving them a common class value.

The outer <span> copy is then attached with a shadow tree (span.attachShadow) made up of a clone of the template’s content (keyPointsTemplate.cloneNode(true)).

This “attachment” causes the <slot> inside the template’s list item in the shadow tree to absorb the inner <span> carrying its matching slot name, i.e. our key point.

The slotted key point is then added to the key points section at the end of the page (keyPointsSection.appendChild(span)).

This happens with all the key points in the course of the loop.

That’s really about it. We’ve snagged all of the key points in the article, made copies of them, then dropped the copies into the list template so that all of the key points are grouped together providing a nice little CliffsNotes-like summary of the article.

Here’s that demo once again:

See the Pen
Text Extraction with HTML Slot and HTML Template
by Preethi Sam (@rpsthecoder)
on CodePen.

What do you think of this technique? Is it something that would be useful in long-form content, like blog posts, news articles, or even Wikipedia entries? What other use cases can you think of?

The post Extracting Text from Content Using HTML Slot, HTML Template and Shadow DOM appeared first on CSS-Tricks.

CSS-Tricks

, , , , , , , ,
[Top]

HTML, CSS and our vanishing industry entry points

Rachel Andrew:

There is something remarkable about the fact that, with everything we have created in the past 20 years or so, I can still take a complete beginner and teach them to build a simple webpage with HTML and CSS, in a day. We don’t need to talk about tools or frameworks, learn how to make a pull request or drag vast amounts of code onto our computer via npm to make that start. We just need a text editor and a few hours. This is how we make things show up on a webpage.

That’s the real entry point here and yes, in 2019 they are going to have to move on quickly to the tools and techniques that will make them employable, if that is their aim. However those tools output HTML and CSS in the end. It is the bedrock of everything that we do, which makes the devaluing of those with real deep skills in those areas so much more baffling.

Speaking of entry points, I compiled a bunch of ideas for how and where to learn HTML and CSS for the present day.

Direct Link to ArticlePermalink

The post HTML, CSS and our vanishing industry entry points appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

Where Do You Learn HTML & CSS in 2019?

The topic of how accessible it is for newbies and seasoned developers alike to learn CSS has been gaining steam as the complexity of the tools around it has become skewed more toward traditional programming. Rachel Andrew has much more to say about this in her post, HTML, CSS and our vanishing industry entry points. Robin also has thoughts on where and how to learn CSS in the modern age.

The question of how and where to learn CSS is a highly reasonable thing to ask. The answer depends on all sorts of things: how serious you are, your current foundation, what other resources are available to you, what you hope to do with what you learn, and how much time you have, among probably a zillion other things.

Let me dump a bunch of possible answers here and you can apply all those “well, that depends” caveats as you see fit.


You could read a book.

There are a ton of books out there that cover HTML and CSS (and often together). They probably all do a fine job. There’s no need to chronicle all the choices here. These two are my personal recommendations. You probably don’t even need both.

Jon Duckett’s is incredibly well-designed and approachable:

Jennifer Robin’s covers a bit more ground and is designed to be useful for either personal reading or classroom learning.

You could read through all the posts in our Beginner’s Guide.

We have a guide (a collection of articles, videos, and links) called Just Starting Out with CSS & HTML. I hope there is stuff in there that can help kickstart or augment your early learning because that’s the intent.

You could go through other free online guides.

Oliver James has a wonderful online course called Internetting is Hard (But it doesn’t have to be).

We designed HTML & CSS Is Hard to be the only introduction to HTML and CSS that you’ll ever need. If you put in the effort to read every section and write every code snippet, this tutorial has the potential to replace hundreds or even thousand of dollars worth of online courses and live training.

A screenshot of a webpage with a white background and large heading that says Basic Web Pages.

Prefer video? Jessica Hische and Russ Maschmeyer’s Don’t Fear the Internet is a super eight-part series that gets you going with HTML & CSS — it even delves into the all-important topic of typography.

A screenshot of the Don’t Fear the Internet webpage, which is sage green, has a large heading with the course title, two columns of text and a video player.

Khan Academy has an Intro to HTML/CSS: Making webpages course that’s packaged in a super cool format. It’s like video in that you get to hear the instructor talk you through the learning, but what you see is a real live text editor and real live output. Sometimes the teacher is controlling the code, and then sometimes it breaks for challenges in which you take over and edit the code yourself.

A screenshot of the Khan Academy course. It has a white background, blue navigation bar across the top, sidebar containing the course contents, and a video player in the main area.

Eric Tirado has an Intro to HTML course on Scrimba, which is also a neat platform in that Eric’s voice guides you through the course, but visually it’s a combination of slides with a real code editor and preview.

A screenshot of the Scrimba course. It resembles a code editor with a dark gray background, sidebar outlining web assets, and an editor with code in the main area.

You could find and take a paid online course.

I often join gyms because the accountability of paying for something gets me to do it. I know I can do situps, pushups, and go for a jog for free, but the gym membership makes a thing of it. Well, same could be said about paying for a course on HTML and CSS.

These are broad generalizations, but good places to start:

You could go to a code school or coding bootcamp

If you wanna put even more skin in the game, you could consider literally going to school. If you don’t have a college degree, that’s an option, although you’ll be looking at a broad education rather than a ticket to leveling up your web design and development skills alone. I’m a fan of that just for the general mind-broadening it involves.

But assuming you’re going to go to a coding-specific school…

There are probably dozens — if not hundreds — more, so this is more to inform you of the possibility of schooling. You don’t even have to go to a physical school since plenty of these offer online courses, too (but with the advantage of live instruction and cohorts). For example, LambdaSchool has the novelty of being free to start and paid later in the form of letting them take a portion of your salary after you get a job in the industry.

You could practice on CodePen.

Not every second of your learning should be strictly following some course laid out by a book, class, or teacher. It wouldn’t even be that way if you tried. You might as well embrace that. If something tickles your muse, go play! I hope CodePen is a rewarding place to do that, making it both easy and useful, while providing a place to connect with other folks in the field.

You could build a personal site and learn what you need to get it done.

That’s how absolutely countless developers have cut their teeth, including me. I wanted a personal website years ago, and I struggled through getting a self-hosted WordPress site online so I could have full control over everything and bend it to my will. Once you have an actual website online, and you know at least some people are seeing it, it gives you all the motivation in the world to keep going and evolve further.

The way you actually learn is going to be a combination of all this stuff.

People are obsessed with asking musicians if they’re self-taught. Like, if they are, their amazingness triples because it means their creative genius was delivered by a lightning bolt at birth. They don’t need anyone else to learn; they merely look at those guitar strings and know what to do.

And if they were taught be a teacher, then, well, that’s all out the door. If they are good at all, then it’s because the teacher delivered that to them.

Total nonsense.

People learn anything — music and web development included — inside a hurricane of influences. Let’s stick with music for a second. Learning to play comes in many forms. You learn by listening to music an awful lot. You can do fundamental practice, like finger exercises and going up and down scales. You can learn to transpose chords on a chalkboard. You can watch YouTube all day and night. You can sign up for online courses. You can go to local jams to watch and play along. You can join a band. You can take lessons from someone advertising on Craigslist. You can go to a local music school. You can read books about music.

You get the idea.

You can and probably will do all of that. With learning web design and development, getting anywhere will involve all sorts of ways. There’s no silver bullet. It takes bashing on it lots of different ways. There’s no requirement to sprinkle money on it, but you do need multiple angles, time, and motivation.

Go forth and build websites!

The post Where Do You Learn HTML & CSS in 2019? appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

Designing for the web ought to mean making HTML and CSS

David Heinemeier Hansson has written an interesting post about the current state of web design and how designers ought to be able to still work on the code side of things:

We build using server-side rendering, Turbolinks, and Stimulus. All tools that are approachable and realistic for designers to adopt, since the major focus is just on HTML and CSS, with a few sprinkles of JavaScript for interactivity.

And it’s not like it’s some well kept secret! In fact, every single framework we’ve created at Basecamp that allows designers to work this way has been open sourced. The calamity of complexity that the current industry direction on JavaScript is unleashing upon designers is of human choice and design. It’s possible to make different choices and arrive at different designs.

I like this sentiment a whole lot — not every company needs to build their websites the same way. However, I don’t think that the approach that Basecamp has taken would scale to the size of a much larger organization. David continues:

Also not interested in retreating into the idea that you need a whole team of narrow specialists to make anything work. That “full-stack” is somehow a point of derision rather than self-sufficiency. That designers are so overburdened with conceptual demands on their creativity that they shouldn’t be bordered or encouraged to learn how to express those in the native materials of the web. Nope. No thanks!

Designing for the modern web in a way that pleases users with great, fast designs needn’t be this maze of impenetrable complexity. We’re making it that! It’s possible not to.

Again, I totally agree with David’s sentiment as I don’t think there’s anyone in the field who really wants to make the tools we use to build websites overly complicated; but in this instance, I tend to agree with what Nicolas recently had to say on this matter:

The interesting thing to note here is that the act of front-end development changes based on the size and scale of the organization. As with all arguments in front-end development, there is no “right” way! Our work has to adapt to the problems that we’re trying to solve. Is a large, complex React front-end useful for Basecamp? Maybe not. But for some organizations, like mine at Gusto, we have to specialize in certain areas because the product that we’re working on is so complicated.

I guess what I also might be rambling about is that I don’t think it’s engineers that are making front-end development complicated — perhaps it’s the expectations of our users.

Direct Link to ArticlePermalink

The post Designing for the web ought to mean making HTML and CSS appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

The practical value of semantic HTML

I love how Bruce steps up to the plate here:

If the importance of good HTML isn’t well-understood by the newer breed of JavaScript developers, then it’s my job as a DOWF (Dull Old Web Fart) to explain it.

Then he points out some very practical situations in which good HTML brings meaningful benefits. Maybe benefits isn’t the right word, as much as requirement since most of it is centered around accessibility.

I hope I’ve shown you that choosing the correct HTML isn’t purely an academic exercise…

Semantic HTML will give usability benefits to many users, help to future-proof your work, potentially boost your search engine results, and help people with disabilities use your site.

I think it’s fair to call HTML easy. Compared to many other things you’ll learn in your journey building websites, perhaps it is. All the more reason to get it right.

Estelle Weyl has some similar thoughts:

… take the radio button. All you have to do is give all the radio buttons in your button group the same name, preferably with differed values. Associate a label to each radio button to define what each one means. Simply using allows for selecting only one value with completely accessible, fast keyboard navigation. Each radio button is keyboard focusable. Users can select a different radio button by using the arrow keys, or clicking anywhere on the label or button. The arrows cycle thru the radio buttons, going from the last in the group to the first with a click of the down or right arrow. Developers don’t have to listen for keyboard, mouse, or touch interactions with JavaScript. These native interactions are robust and accessible. There is rarely a reason to rewrite them, especially since they’ll always work, even if the JavaScript doesn’t.

Direct Link to ArticlePermalink

The post The practical value of semantic HTML appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

Get References from HTML Built with Template Literals

One thing JavaScript template literals are great at is little blocks of HTML. Like:

// Probably from some API or whatever const data = {   title: "Title",   content: "Content" };  const some_html = `   <div class="module">     <h2>$  {data.title}</h2>     <p>$  {data.content}</p>   </div> `;

But that’s still just a string. It’s not ready to append to the DOM just yet. And what if we need references to those elements inside somehow?

We’ve written about a couple of libraries that are in this vein: lit-html and hyperHTML. Those are pretty small libs, but are also sorta more about re-rendering of templates in an efficient way (like super mini React).

What if you just need the nodes? That’s almost a one-liner:

const getNodes = str => {    return new DOMParser().parseFromString(str, 'text/html').body.childNodes; }

Now we could drop that template literal of HTML right into the DOM:

document.body.appendChild(getNodes(some_html)[0]);

Here’s that:

See the Pen pQyZOz by Chris Coyier (@chriscoyier) on CodePen.

But how do we get our hands on individual bits of that HTML? We don’t exactly have references to anything, even the whole chunk we put in.

I just saw this little lib called Facon that looks to do just this. It makes use of tagged template literals, which is super cool:

import f from 'facon';  const data = {   title: "Title",   content: "Content" };  let html = f`   <div class="module">     <h2>$  {data.title}</h2>     <p>$  {data.content}</p>   </div> `;  document.body.appendChild(html);

This skips the need for our little getNodes function, but more importantly, we can yank out those references!

let html = f`   <div class="module">     <h2 ref="title">$  {data.title}</h2>     <p ref="content">$  {data.content}</p>   </div> `;  let { title, content } = html.collect(); title.innerText = "Title Changed!";

Here’s that:

See the Pen Facon Template by Chris Coyier (@chriscoyier) on CodePen.

The post Get References from HTML Built with Template Literals appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]