PROFESSIONALLY OPTIMIZED WEBSITES STARTING AT $295
Our team of SEO Web Design gurus are standing by to assist you achieve your online marketing goals.

+1-971-599-3330

REQUEST QUOTE
SEO Web Design, LLC aims to improve business by delivering effective solutions based on innovative technologies and professional designs. Discover the variety of services we offer and convince yourself on the basis of the latest works that we've done. We love building fresh, unique and usable websites optimized specifically for your niche.

Responsive Web Design

SEO / SEM / Social Media

Conversion Rate Optimization

Email Marketing

Online Presence Analysis

Web Hosting
Top
SEO Web Design, LLC / Web Design  / A Web Component with Different HTML for Desktop and Mobile

A Web Component with Different HTML for Desktop and Mobile

Christian Schaefer has a great big write-up about dealing with web advertisements[1]. The whole thing is interesting, first documenting all the challenges that ads present, and then presenting modern solutions to each of them.

One code snippet that caught my eye was a simple way to design a component that renders different HTML depending on the screen size.

<div class="ad">
  <template class="ad__mobile">
    // Mobile ad HTML code with inline script
  </template>
  <template class="ad__desktop">
    // Desktop ad HTML code with inline script
  </template>
  <script>
    const isMobile = matchMedia('(max-device-width: 20em)').matches;
    const ad = document.currentScript.closest('.ad');
    const content = ad
      .querySelector(isMobile ? '.ad__mobile' : '.ad__desktop')
      .content;
    
    ad.appendChild(document.importNode(content, true));
  </script>
</div> 

Clever. Although note that Christian ends up going a totally different route in the article.

Here’s that same code where I use a custom element and move the JavaScript to JavaScript just ‘cuz.

See the Pen
A Web Component with Different HTML for Desktop and Mobile
[2] by Chris Coyier (@chriscoyier[3])
on CodePen[4].

Powered by WPeMatico

[email protected]

CSS-Tricks.com offers daily articles about CSS, HTML, JavaScript, and all things related to web design and development.

No Comments

Sorry, the comment form is closed at this time.