Web Dev Snippets

September 3, 2019

Snippets

Web Dev

These are just raw notes on web development. They aren’t necessarily organized in any specific way, this is more of a board to place things I learn about the field. I used to have these unorganized within the notes app on my phone, but by placing them here I hope that someone else can use them too. If you have any questions on the notes or a question on a particular snippet feel free to reach out to me using the form at the bottom of this page.

Some users reduce their data consumption by entering a “lite” mode or turning on a “data saver” feature. When this happens, browsers will often send a Save-Data header with their network requests. 

More info on that here

Responsive Image code:

<img src="medium.jpg"
  srcset="small.jpg 256w,
    medium.jpg 512w,
    large.jpg 1024w"
  sizes="(min-width: 30em) 30em, 100vw"
  loading="lazy"
  alt="Descriptive text about the picture.">

A simple and perfect CSS reset:

*,
*::before,
*::after {
   box-sizing: border-box;
}

ul[class],
ol[class] {
   padding: 0;
}

body,
h1,
h2,
h3,
h4,
p,
ul[class],
ol[class],
li,
figure,
figcaption,
blockquote,
dl,
dd {
   margin: 0;
}

body {
   min-height: 100vh;
   scroll-behavior: smooth;
   text-rendering: optimizeSpeed;
   line-height: 1.5;
}

ul[class],
ol[class] {
   list-style: none;
}

a:not([class]) {
   text-decoration-skip-ink: auto;
}

img {
   max-width: 100%;
   display: block;
}

article > * + * {
   margin-top: 1em;
}

input,
button,
textarea,
select {
   font: inherit;
}

@media (prefers-reduced-motion: reduce) {
   * {
      animation-duration: 0.01ms !important;
      animation-iteration-count: 1 !important;
      transition-duration: 0.01ms !important;
      scroll-behavior: auto !important;
   }
}

To smooth out text:

-webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;

To optimize images for web:

Run it through Squoosh.app

Convert to webp and jpeg2000 in iTerm with ImageMagick:
convert path/to/file.png -quality 50  path/to/file.webp
convert path/to/file.png -quality 50  path/to/file.jp2

Convert to mobile sizes (resizing is proportional, the number is the width):
convert path/to/file.png -resize 300  path/to/file-mobile.png

Then add the following markup:

<picture>
   <source type="image/webp" srcset="path/to/image.webp">
   <source type="image/jp2" srcset="path/to/image.jp2">
   <source srcset="path/to/image.jpg" alt="description" media="(max-width: 961px)">
   <img src="path/to/image.jpg" alt="description" />
</picture>

HTML Notes

To edit anything on a webpage open the console and type document.designMode = “on” then hit enter.

Check if user is on Internet Explorer:

<script type="text/javascript">
   // Detect if using Internet Explorer
   if (navigator.appName == 'Microsoft Internet Explorer' ||  !!(navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/rv:11/)) || (typeof $.browser !== "undefined" && $.browser.msie == 1)) {
      // do something
   }
</script>

Lazy Load background images:

document.addEventListener('lazybeforeunveil', function(e){
   var bg = e.target.getAttribute('data-bg');
   if(bg){
      e.target.style.backgroundImage = 'url(' + bg + ')';
   }
});

Then add class=”lazyload” and data-bg=”/path/to-image.png” to element.

Smooth scroll on link click:

$("a").on('click', function(event) {
   if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
         scrollTop: $(hash).offset().top - 100
      }, 800, function(){
         window.location.hash = hash - 100;
      });
   }
});

Users today are fearful that their information will be used for nefarious purposes. Make it a point to reassure them that their data is safe. Our testing showed that the best way to do this is to add a link to the privacy policy (“Your information is secure!”) with a little lock icon right next to the submit button. Users will often skip right over a small text link, so that lock icon is essential

The worst thing you can put on a submit button is the word “Submit.” We found that switching this button copy out with “Request Information” showed a significant improvement. Think about the implied direction of the interaction. “Submit” implies the user is giving something to us; “Request Information” implies we’re giving something to the user. The user is already apprehensive about handing over their information—communicate to them that they’re getting something out of the deal. 

Form headings should ask the user to do something. It’s one thing to label a form “Request Information”; it’s another to ask them to “Request Information Now.” Simply adding action words, like “now” or “today,” can change a description into an imperative action and improve conversion rates.

In the Network—>Time column of Inspector when the two numbers are very similar (i.e. 77ms, 74ms) the limiting factor there is latency. Reducing file size won’t do much. When the two numbers are far apart(i.e 124ms,30ms) the limiting factor is bandwidth, reducing file size on these will help.

Picking a bright color that stood out from the rest of the site for the submit button did show an improvement in conversions, and reducing clutter around the call to action improved conversion rates by 232%.

Buttons should be large, forms should be hard to miss, and language should be imperative. A call to action should be one of the first things the user notices on the page, even if he or she won’t be thinking about it again until after doing some research on the page

More verbose code is a trade-off of composition, but it’s a much lesser inconvenience than unscalability

In your sign-up or check-out process, always lead with the information the user is most interested in. In our case, letting the user first select their school campus and area of study showed a significant improvement over leading with contact information. Similarly, put the less-exciting content last. In our testing, users were least excited about sharing their telephone number. Moving that field to be the last one in the form decreased form abandonment and improved conversions.

Figure tags should be used instead of img tags on mostly articles, if it is a figure it can be removed and not effect the flow of the content.

Put scripts in the footer just above the </body> tag, if they must be in the head, add a defer attribute

Bandwidth – the maximum rate of data transfer across a given path

Latency – how long it takes for a bit of data to travel across the network from one endpoint to another

When scrolling use scroll-snap-type to snap to elements. Firefox doesn’t support as of 2/5/19

Simple centering:

.parent { display: flex; }
.child { margin: auto; }

Really nice easing curve:

transition: all cubic-bezier(0.1, 0.67, 0.29, 0.98) 1300ms;

To limit the number of characters in a variable: 

echo mb_strimwidth(get_the_title(), 0, 50, '...');

Parallax Images:

$(document).scroll(function() {
   var scroll = $(window).scrollTop();
   $(".parallax").css("top", "0" + (scroll / 1.8) + "px");
});

.row {
   position: relative;
}

.parallax {
   z-index: 0;
}

If your <script>…</script> blocks have no dependency on CSS, place them above your stylesheets for faster loading.

Try adding in stylesheets with media queries built into the link. The browser will include these stylesheets even on desktop (just prioritized last) because of the edge case that the user will resize the browser window. Here’s an example:

<link href=“mobile.css” rel=“stylesheet” media="screen and (max-width: 600px)">

To fix weird styling on buttons on mobile:

input {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

 Center an absolutely positioned item:

.something {
   position: absolute;
   left: 50%;
   transform: translate(-50%, -50%);
}

Segment conditional:

<?
$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);
if ($uri_segments[0] == 'string') {
   // do something
}
?>

For bootstrap equal height columns give the row a class of row-eq-height. Add this to the css file:

.row-eq-height {
   display: -webkit-box;
   display: -webkit-flex;
   display: -ms-flexbox;
   display: flex;
}

Looping while creating bootstrap rows:

<? $i=0; // counter ?>
<? while ( have_posts() ) : the_post(); ?> 
   <? if ($i%3==0) { // if counter is multiple of 3 ?>
      <div class="row">
   <? } ?>
   <div class="col-md-4">
      Content...
   </div>    
   <? $i++; ?> 
   <? if($i%3==0) { // if counter is multiple of 3 ?>   
      </div>
   <? } ?>
<? endwhile; ?>
<? if($i%3!=0) { // put closing div if loop is not exactly a multiple of 3 ?>
   </div>
<? } ?>

To fix CSS flashing (FOUC – flash of unsettled content):

Add this under the meta and title tags in the head:

<style type="text/css">
   .hidden {display:none;}
</style>

<script type="text/javascript">
   $('html').addClass('hidden');
   $(window).on('load', function () {
      $('html').removeClass('hidden'); 
   });  
</script>

Date for copyright year:

<? echo date("Y"); ?>

To strip out a phone number:

<? $phone = preg_replace('/\D+/', '', $phone); ?>

To send SMS Messages: 

Facebook’s Box Shadow:

box-shadow: 0 12px 28px 0 rgba(0, 0, 0, 0.2), 0 2px 4px 0 rgba(0, 0, 0, 0.1), inset 0 0 0 1px rgba(255, 255, 255, 0.5);

@joekotlan on Twitter