Fixed Headers and Jump Links? The Solution is scroll-margin-...
Strategy

Fixed Headers and Jump Links? The Solution is scroll-margin-…


The problem: you click a jump link like <a href="https://css-tricks.com/#header-3">Jump</a> which links to something like <h3 id="header-3">Header</h3>. That’s totally fine, until you have a position: fixed; header at the top of the page obscuring the header you’re trying to link to!

Fixed headers have a nasty habit of hiding the element you’re trying to link to.

There used to be all kinds of wild hacks to get around this problem. In fact, in the design of CSS-Tricks as I write, I was like, “Screw it, I’ll just have a big generous padding-top on my in-article headers because I don’t mind that look anyway.”

But there is actually a really straightforward way of handling this in CSS now.

h3 {
  scroll-margin-top: 5rem; /* whatever is a nice number that gets you past the header */
}

We have an Almanac article on it, which includes browser support, which is essentially everywhere. It’s often talked about in conjunction with scroll snapping, but I find this use case even more practical.

Here’s a simple demo:

In a related vein, that weird (but cool) “text fragments” link that Chrome shipped takes you to the middle of the page instead, which I think is nice.





Source link

Two Dimensional Array example
Strategy

Arrays in C/C++ – DZone Web Dev


C++ provides a data structure, the array, which stores a fixed-size, sequential collection of elements of the same type. They are used to store similar types of elements. (The data type must be the same for all elements.) They can be used to store collections of primitive data types, such as int, float, double, char, etc. of any particular type. To add to it, an array in C or C++ can store derived data types, such as structures, pointers etc.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element, and the highest address to the last element.

If you want to follow video tutorial, check it out below:

You may also like:
The Best of Java Collections [Tutorials].

Array Declaration

To declare an array in C++, the programmer specifies the type of the elements and the number of elements in the array like:

This is called a single-dimension array. arraySize must be an integer constant greater than zero, and type can be any valid C++ data type. For example, to declare a 5-element array of type double, use this statement:

 

There are various ways in which we can declare an array. It can be done by specifying its type and size by initializing it or both.

  1. Array declaration by specifying size 
  1. Array declaration by initializing elements
  1. Array declaration by specifying size and initializing elements 

Advantages of an Array in C/C++:

  1. Random access of elements using array index.
  2. Use less code, as it creates a single array of multiple elements.   
  3. Easy access to all the elements.   
  4. Traversal through the array becomes easy using a single loop.  
  5. Sorting becomes easy, as it can be accomplished by writing less code.

Disadvantages of an Array in C/C++:

  1. Allows a fixed number of elements to be entered, which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  2. Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with new memory allocation.

Example of arrays:

Output: 

   
Example of elements are stored at contiguous memory locations

Output: 

 

Multi-Dimensional Arrays

C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration −

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −

Two-Dimensional Arrays

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y, you would write something as follows:

Type can be any valid C++ data type, and arrayName will be a valid C++ identifier.

A two-dimensional array can be thought of as a table, which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows:

Two Dimensional Array example

Two Dimensional Array example

Every element in an array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays

Multi-dimensioned arrays may be initialized by specifying bracketed values for each row. The following is an array with 3 rows, where each row has 4 columns.

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example −

Accessing Two-Dimensional Array Elements

An element in a two-dimensional array is accessed by using subscripts (i.e., row index and column index of the array). For example:

The above statement will take the 4th element from the 3rd row of the array. You can verify this in the above diagram.

Output:

As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

Pointer to an Array

It is most likely that you would not understand this chapter until you have a decent understanding of pointers.

So, assuming you have bit understanding on pointers in C++, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration:

balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance:

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].

Once you store the address of first element in p, you can access array elements using *p,  *(p+1), *(p+2), and so on. Below is the example to show all the concepts discussed above:

Output:

In the above example, p is a pointer to double, which means it can store an address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example.

Further Reading



Source link

iOS points vs. pixels explained
Strategy

iOS 13 Design Guidelines, Templates, and Downloads – Learn U…


Maybe you’ve never designed an iPhone app, and have no idea where to begin.

Maybe you’ve designed a dozen, but still want one place to reference best practices. Heaven knows Apple’s Human Interface Guidelines are awful to try and read.

Either way, this is the guide for you. I cover basically everything you need to know to create an iOS app that follows standard iOS 13 conventions.

Here’s what we’ll cover today:

  1. Device screen sizes
  2. Page layout
  3. Typography
  4. Navigation
  5. UI elements
  6. App icons
  7. Other iOS conventions
  8. Downloads
  9. Further reading & resources

iPhone Screen Sizes

For the first 5 or 6 years of iPhone releases, screen sizes were pretty manageable. If your design worked on a 320×480 screen, you were golden. Now, it’s the wild west out there. There are 3 new screen sizes from just the last 3 years!

Here’s the full list for your reference (drag this link to bookmark; get the downloadable PDF below)

Device Artboard Size Export Scaling
11 Pro Max, XS Max 414 x 896 @3x
11 Pro, X, XS 375 x 812 @3x
11, XR 414 x 896 @2x
6+, 6S+, 7+, 8+ 414 x 736 @3x*
6, 6s, 7, 8 375 x 667 @2x
5, 5s, 5c, SE 320 x 568 @2x
4, 4s 320 x 480 @2x
1, 2, 3 320 x 480 @1x

*display on phone is technically 2.61x

  • Artboard size. This is the “point size” or “@1x” size of a given device. I strongly recommend designing on artboards of this size for a given device. (Here’s an explanation of points vs. pixels)
  • Export scaling. This is how much bigger to make a raster image (PNG, JPG) when exporting to take maximum advantage of the higher resolution of some devices.

What size artboard should I use for iPhone design?

Use the most common iPhone screen size for your audience, but if you have any dense, data-heavy screens, make sure to test those on smaller screen sizes.

  • If you’re recording analytics on your current app or website, check those* for your audience’s most common screen sizes
  • If you’re designing an app for a general audience, use the overall most popular iPhone screen size: 375×667 pt
  • If you’re designing an app for a tech- or design-savvy audience, the most popular iPhone screen size is likely the newer 375×812 pt

*Google Analytics records this at Audience > Mobile > Devices, and then go to the label that says “Primary Dimension” and set it to “Screen Resolution”

A design that works well on a narrower screen (375pt) will almost certainly work well on a slightly wider screen (414pt) – but the reverse is not true. So it’s always better to design for narrower screens first, then double-check and adjust for larger screens. Since height is less of a constraint, it matters less whether your art boards are, say, 667 or 812 pixels tall.

iOS Points vs. Pixels

A “point” is a measure for designers to compare the sizes of fonts and UI elements across iOS devices. A “pixel” is a tiny square of light that your iPhone screen is made up of. Smaller pixels mean a clearer image, which is great. But if you merely make your pixels smaller, everything on the screen would get smaller too! To balance this, designers measure the size of elements on the screen in points. Once pixels were half as tall/wide as they started, we could just use a 2×2 square of pixels for every point (this is called @2x). And once pixels were roughly a third as tall/wide as they started, we could use a 3×3 square of pixels for every point.

iOS points vs. pixels explained

Points is the unit that allows us to have higher resolution screens without all the elements on the page just shrinking. Yay, points! That being said, occasionally designers use the terms interchangeably, and you’ll just have to know from context which they mean. Boo, designers.

Page Layout

While different iOS apps have different layouts, many standard pages will have a layout something like the following:

iPhone design template

Note: in the downloads section below, I have an iPhone Sketch template that has rulers dividing these page areas, plus the status bar and home indicator. It allows you to start filling in this framework of the page very quickly.

If you’re interested in a specific section of the page, you can skip ahead to that section:

Status Bar

The status bar appears at the top of every page – except for some full-screen images, videos, or media.

iOS status bar on iPhone X and newer

The status bar contains the time, signal, wifi, and battery indicators, and can be written (text and icons) in either black or white.

The background to the status bar can be any color – or even transparent. To find variations on a color that contrast suitably against white, use the Accessible Color Generator.

iOS transparent status bar design

If you’re using a status bar on anything except the lightest of images, you’ll probably want to use white text.

Or, if you want a minimal status bar over a variety of images, use a background blur.

iOS background blurred status bar design

This “frosted glass”-style status bar doesn’t add any additional colors, borders, or needlessly attention-attracting elements to the interface – it merely blurs whatever colors are below it, making the text more readable.

In the example above, the light gray page background color is the “default” color of the frosted glass, meaning the text above it should be black – not white.

Only since iPhone X do iPhones have the “notch” design and rounded corners on the border. Older iPhones (and all iPads) have a shorter, more compact status bar.

iPhone 8 and earlier status bar design

The nav bar is where the app displays navigation (surprise!), the page title, primary page actions, and – often – search.

You can think of the iOS nav bar as being comprised of up to three “rows”.

In my iPhone UI Sketch Template, I include guides at all of these demarcating where these rows typically sit.

iPhone design template
  • Status bar: 44pt tall
  • First row: 44pt tall
  • Second row: 54pt tall
  • Third row: 48pt tall

(These measurements are not always exact, and iOS default apps deviate from them somewhat, but they will get you started)

So an iPhone app will show one, two, or three rows, depending on (a) the needs of the page and (b) the scroll state.

Use a single row if you just need to compactly display some page actions (even the page title is optional).

iOS nav bar with single row

However, if you can afford the space, the default iOS app page layout contains two rows: one for page actions, and a second for a large page title.

iOS nav bar with two rows

But if you need to show search, then you need a third row (even if the first row is left blank!).

iOS nav bar with three rows

Now the screenshots above only show the pre-scrolled behavior. As soon as the user starts scrolling, iOS specifies for some interesting behavior.

iPhone nav bar scroll behavior

If a search bar is important to see at all times, it merely moves up from the third row to the second row while the app is scrolled.

If it’s less important, it will disappear entirely – only visible when the user is at the very top of the page.

When iOS nav bar rows disappear upon scrolling, they will re-appear when the user scrolls back to the top.

title

Note that the transitions between states is animated totally smoothly – a small, yet characteristic detail of the iOS style.

Tab Bar

On iOS apps, primary destinations in the app are listed as tabs across the bottom.

iPhone tab bar design

Let’s note a few things styling-wise:

  • The selected icon is denoted with the app theme fill color
  • The labels are 10-11pt text in SF, the default font
  • The background can be ever-so-slightly translucent and have a background blur – the “frosted glass” effect, a la the nav bar

And a few notes on the behavior of the tab bar and its buttons:

  • Different tabs remember their state. If you travel to a certain destination in one tab, switch to another tab, then switch back to the first tab, you’ll be where you left off in that tab – not the “main screen” for that tab
  • If you tap the active tab, you’ll return to the “main screen” for that tab
  • The tab bar is always visible within the app, except:
    ** When a keyboard is shown
    ** When a modal is open (during critical tasks, the user should focus on the task at hand rather than navigate to other parts of the app)
iPhone tab bar with 'More' tab design

There should be 2-5 tabs in total. If you need to display more than 5, the fifth icons should be a “More” catch-all that shows other destinations on a quasi-picker screen when tapped.

Home Indicator

New iPhones (X and more recent) all have a home indicator – a thin, rounded bar omnipresent at the bottom of the screen. Well, omnipresent except for when you’re already on the home screen.

iPhone home indicator in light mode

It is black on all light screens, but can be made white on darker screens.

iPhone home indicator in dark mode

And by dragging it up some amount, you can navigate between apps and to the home screen:

  • Drag a short ways up: go to app switcher screen
  • Drag a long ways up: go to home screen

Usually, the home indicator “owns” its own 34pt tall “box” that no other fixed elements can be shown in.

iPhone home indicator with keyboard design

But scrollable lists can be shown scrolling under the home indicator – and you can even select the item directly under the home indicator by tapping. The home indicator only responds to swiping up.

iPhone interaction tapping button below home indicator

Primary App Destinations

Navigating between the main areas of the app is covered in the Tab Bar section.

Back

On iOS, you can navigate backwards in 4 different ways, depending on the context.

Method of Navigating Back Context in Which it Works
Tap “Back” action on top-left of screen Any screen on which a “Back” action appears
Swipe right from left edge of screen Any screen on which a “Back” action appears
Tap “Cancel” or “Done” action on top of screen Modal views
Swipe down on screen content Modal or fullscreen (e.g. photos, other media) views

The top 2 ways usually apply to the same screens.

navigating back in an iOS app
On most screens, you can navigate back by (1) the top-left action or (2) swiping right from the left edge.

See the modals section below for more on how to navigate away from them.

There are 3 primary entry points to search in Phone apps:

  1. The search bar in the nav bar
  2. A search icon in the nav bar
  3. A search icon in the tab bar
search design patterns on iOS apps

However, no matter where the search entry point is, the search experience looks fairly similar:

search UX patterns on iOS app

Optionally, you can show popular or recent searches below the search box. I cover some of the best practices for search experiences in my course on designing intuitive, easy-to-use apps, Learn UX Design.

Some tasks involve a single screen – or a linear series of screens – that you want users to complete without totally leaving the context they were in.

In iOS 13, we now have a perfect UI element for that: the modal sheet.

A modal sheet is a normal page that (a) slides up from the bottom covering almost all of the previous page, but (b) leaves the previous page visible, yet recessed, in the background.

iOS modal sheet animation

Modals can be dismissed by:

  • Pressing the “close”-like action at the top (above, it’s “Cancel” in the upper-right)
  • Swiping down on the modal card itself

UI Elements & Controls

Lists (AKA Table Views)

Remember: “90% of mobile design is list design”. If you want to get good at designing iPhone apps, learn how Apple thinks about its lists (or, as they say “Table Views”).

Any time you’re making a list on iPhone, you need to ask yourself three questions:

  1. What text do I want to display?
  2. Do I also want an icon/image?
  3. What goes in the right half of the cell?

Let’s cover each of these in turn.

What text do you want to display on each list item? You can choose:

  1. Only primary text (17pt regular)
  2. Primary text (17pt regular) with secondary text (15pt regular)
  3. Custom layout – e.g. primary text (17pt regular), secondary text (15pt regular BUT LIGHTER) and tertiary text (15 regular BUT LIGHTER STILL)
iOS list design types

To the left of the text, you can optionally display an icon or image.

image or icon in iOS list

Finally, there are a handful of options for the right-hand side of a list item:

  • A (right-pointing) chevron. Almost the default, this lets users know they’ll be navigating to another screen
  • Text and a chevron. This means the user can navigate to another screen to choose the value to be shown here
  • A checkmark. Allows the user to choose between one of the list items in that group (Note: not multi-choice, as web checkbox lists are)
  • Switch. Allows the user to toggle the property that list item refers to on or off.
  • Text buttons. Use a system color to link to another page or flow. Use red text to represent a “destructive action” – turning something off, deleting it, removing it, etc.
options for right-hand accessory for iOS list UI

There are more iOS paradigms for what you can do with lists not covered here – but this is an overview of some of the most common ways to using lists. For more, check out input controls.

Buttons

Usually we think of buttons as being colored rectangles with centered text – and iPhone apps certainly use those kinds. But if you’re coming from the world of web design, you might be surprised to realize that many buttons on iOS are simply either (a) icons or (b) colored text – in either (a) the nav bar (at the top of the screen) or (b) action bar (at the bottom of the screen).

iOS buttons on nav bar and action bar

However, iOS does have on-page buttons as well.

iOS buttons on page cards, icons, and text

Because page-wide actions appear on fixed menus (the nav bar or action bar), many on-page buttons apply only to a certain part of the page – and hence will appear on cards.

Input Controls

One non-obvious thing about how iOS apps do input controls is they’re almost all styled as list items.

Text boxes

Text inputs appear like a list item with a hint that disappears on typing.

iOS text input control

Switches

Switches appear within a list item with the label on the left and the binary choice switch on the right.

iOS switch control

Date and/or time pickers

At first, it appears just like a list item with the label on the left and the value on the right, but if you tap on the list item, it expands into a special “spinner” control.

iOS date picker control

You can modify this to pick (a) just a time, (b) just a date, (c) both a time and a date, or (d) some other custom value. That being said, I recommend against using this as a universal replacement for dropdowns. Instead, on mobile, you’ll often want to use the “picker screen” pattern – which is a great lead-in ?

Picker screens

If you’re ever tempted to use a dropdown (which you shouldn’t be – but let’s pretend), you probably should be using the picker screen pattern on iPhone apps. The whole idea is that you have something resembling a list item, but it actually leads to another page where you pick the value.

iOS picker screen control

So, the ingredients:

(1) A single list item with a label, value, and chevron leads to (2) a page with many options in a list, one of which can be selected, and will show this state with a checkmark.

Once you’ve made your selection, you can navigate back with a swipe or by pressing the button in the upper-left.

Typography

For more on iOS typography (and, in particular, font sizes), see my full article on it here.

iOS has a distinctive paradigm for styling text. Perhaps the most surprising lesson is that where many design systems style with size or uppercase, iOS styles with weight or color. We’ll unpack this lesson looking at many of the text styles across iPhone apps. Here’s a quick reference in case you want to skip ahead:

Element Type Style
Page title (unscrolled) 34pt bold #000
Page title (scrolled) 17pt medium #030303
Paragraph text,
List item titles,
Links
17pt normal #000
Secondary text 15pt normal #8A8A8E
Tertiary text,
Captions
13pt normal #8D8D93
Buttons,
Text input controls
17pt normal, various colors
Action bar labels 10pt regular #8A8A8E

Title Text

Page titles are written in two distinct ways on iPhone apps.

title text styling for iOS app design

When the user hasn’t scrolled yet (or has scrolled, but then scrolled back to the top):

  • Size: 34pt
  • Font weight: bold
  • Color: #000
  • Dark mode color: #FFF
  • Alignment: left

When the user has scrolled down:

  • Size: 17pt
  • Font weight: medium
  • Color: #030303
  • Dark mode color: #FFF
  • Alignment: center

Default Text

The “default style” for text on iPhone apps is:

  • Size: 17pt
  • Font weight: normal
  • Color: #000
  • Dark mode color: #FFF
default text styling for iOS app design

You can get a lot of mileage by making slight tweaks to this basic style.

variations of the default text styling for iOS app design

For instance, while normal list items are written with the default text style, the Mail app shows email senders in bold – as it helps the sender’s name stand out from the subject line and preview.

Likewise, text-based link buttons are basically the default text, but with different colors.

And search field hint text is the default text, but a lighter gray.

Secondary Text

iPhone apps have a standardized style for any supporting “secondary” text.

  • Size: 15pt
  • Font weight: normal
  • Color: #8A8A8E
  • Dark mode color: #8D8D93
secondary text styling for iOS app design

Tertiary Text & Captions

Any explanatory “captions” are given an even smaller, lighter treatment than secondary text.

  • Size: 13pt
  • Font weight: normal
  • Color: #6D6D72
  • Dark mode color: #8D8D93
tertiary text styling for iOS app design

Minimum Text Size

With any design system, it can save you a lot of headache to just define a minimum size. For iPhone apps, that’s the action bar labels, at 10pt:

  • Size: 10pt
  • Font weight: normal
  • Color: #999 (when unselected)
  • Dark mode color: #757575 (when unselected)
minimum text styling for iOS app design

App Icons

If you design an app icon specifically at the size that it appears in every possible location for every possible iPhone and iPad, you will end up needing to create a dozen variations of the same icon.

You’re welcome to do that.

(If you use Sketch, you can do it rather simply with their template – File > New from Template > iOS App Icon)

However, if you’re like me, you’d rather make sure the more common sizes on the more common (or newer) devices are covered, and call it. After all, isn’t the whole point of this @3x business that the individual pixels are too small to see?

Here’s Erik’s 80/20 iPhone app icon design plan:

  1. Create a square icon that looks good at 60x60px (and verify it looks good masked with the Apple superelljpse*)
  2. Blow it up to @2x (120x120px) and optionally adjust it to be as pixel-perfect as you’d like
  3. Blow it up to @3x (180x180px) and optionally adjust it to be as pixel-perfect as you’d like
  4. Blow it up to 1024x1024px
  5. Export all 4 sizes as PNGs. Done ?

The iOS Superellipse (AKA “Squircle”) Icon Shape

Even though you should always export your icons as squares, Apple will cut out the corners using a type of shape called a superellipse.

Apple superellipse squircle vs rounded rectangle icon design

A superellipse – or squircle – looks a lot like a normal rounded rectangle. In fact, the difference is basically invisible to the naked eye. Apple’s rationales for the swtich are (a) a superellipse more gently transitions from the straight part to the curved part, leading to an overall more organic shape, and (b) this aligns better with the corners of Apple’s hardware devices.

This really only matters if your icon has a border, in which case your border shape should be determined by a superellipse, not a rounded rectangle. Here’s how to create a superellipse/squircle in Sketch and Figma:

How to create an Apple icon superellipse/squircle in Sketch

  1. Create a square using the Insert menu or shortcut “r”
  2. Change the corner radius to the length of one size multiplied by 0.222
  3. Change “Radius (Round Corners)” to “Radius (Smooth Corners)”

How to create an Apple icon superellipse/squircle in Figma

  1. Create a square using the Rectangle menu item or shortcut “r”
  2. Change the corner radius to the length of one size multiplied by 0.222
  3. Open the Independent Corners menu (just to the right of the corner radius setting)
  4. Open the Corner Smoothing menu (the “…” icon) and set it to the “iOS” indicator, located at 60%

Other iOS conventions

There are a couple other things you should probably know about if you’re designing an iPhone app. I will just go ahead and list them here:

Tap Target Size

Everything the user should be able to tap on – every button, every slider, every input control – should be at least 44×44 pts in size.

The only exception where it’s really excusable to break this is text links. In paragraph text, each line of text will likely be quite a bit shorter than 44pt. That means that (a) your links will have tap target of less than 44pt size and (b) if there are links in the same position in two consecutive lines of text, it will be pretty difficult for users to tap them accurately. While this can’t always be avoided, it’s worth knowing about this as something to minimize.

tap target size for iOS app design
Even Apple does not keep strenuously to their tap target guidelines – though I suggest you do anyways.

Dark Mode

As of iOS 13, iOS has an OS-level “dark mode” setting, where participating apps have (generally) dark backgrounds and light text, instead of light backgrounds and dark text.

iPhone app dark mode vs. light mode comparison

While iOS will automatically transition to the dark version if you’re using native controls and colors, you should understand the general principles of dark mode for any custom UI you do. Here are a few simple guidelines:

  • Text colors are inverted. It’s a bit of an oversimplification, but black text becomes white, dark gray text becomes light gray text, and middle gray text stays basically the same. If you look at the typography styles above, you’ll notice iOS actually drops a few extra shades and simplifies the text colors for their dark theme. If you can’t tell whether you should make a middle-brightness gray darker or lighter, go with the option that has a higher contrast text contrast against its background.
  • Background colors are shifted. Unlike text, where darker colors become lighter, the background colors are all just shifted darker. If a background color was lighter in light mode, it’s still lighter in dark mode. Why? Because light comes from the sky. If you understand that, you’ll understand we’re relying on background color for depth cues (unlike text). And so it works in a totally different way.
  • Theme colors are translated to pop against dark. Any accent colors that you were previously using on light backgrounds now need to pop similarly against dark backgrounds. Since white has a brightness of 100% and black has a brightness of 0%, this often means you’ll be lowering the brightness of bright colors (and, in my greater theory of color adjustments, raising their saturations).
iOS color comparison light mode vs dark mode
Colors taken from iOS System Colors.

Creating dark UI is its own topic, deserving of its own guide – and its one of the things I cover in a lot more depth in Learn UI Design.

Downloads

I’ve created a few resources for easy reference. Links and descriptions below ?

iPhone Screen Size Cheatsheet

Pixels, points, inches, oh my. This is a quick guide to each version’s iPhone’s screen size and resolution.

? FREE DOWNLOAD

iPhone 11 Design Template

This Sketch file (which you can also open in Figma) includes an iPhone 11 artboard with (a) rulers to make off common sections of the screen, (b) a mask with the notch and rounded corners, and (c) an easy-to-recolor status bar. Once you’ve downloaded it, open it in Sketch and choose File > Save as Template for easy access.

? FREE DOWNLOAD

Further Resources

Apple’s Human Interface Guidelines for iOS. Apple’s own standards are notoriously difficult to read through. First you have to wade through their abstract principles, and you constantly face an uphill battle against their hackneyed terminology (why are lists called “Tables” and filed under “Views”!? Shouldn’t that be under “Controls”? No, but apparently plain text is a “control” – just look under “Labels”!). Anyhow, I will say that once you adjust your mindset, the Apple cool-aid makes a lot more sense, and – let’s face it – if you’re designing an iPhone app, you’re going to be here anyways. Best get used to it.

iOS vs. Android App UI Design: The Complete Guide. OK, let’s say you think you’re going to be making an Android version of your iPhone app at some point. Best to start thinking about some of the design differences now. Who knows – you may end up stealing some great ideas from Android design principles. This article actually covers a few iOS design paradigms that I didn’t get to here. Worth the read!

The iOS Font Size Guidelines. One of the most unexpected parts of getting good at UI design is developing an intuitive sense of what font sizes to use. So, to help with that, I wrote the world’s most comprehensive guide to font sizes. One part is one iOS apps, and if you’ve gotten this far, you should probably read that too.

Ivo Mynttinen’s iOS Design Guidelines. The most comprehensive guide I could find besides this one on making human-readable iPhone app guidelines (besides this one ?). Fantastic read.

Wrapping it up

Did I miss anything? Something look wrong? Give me a shout at [email protected]. I’ll be continually updating this guide to be the most accurate and human-readable guide on the web for creating iPhone apps.

One Final Note ?

If this is your first time here, you might also be interested in:

  • Learn UI Design, my full-length online video course on user interface design
  • The Design Newsletter, a 30,000+ person newsletter with original design articles aimed at giving you tactical advice to improve your UX/UI skills.

Some people have some really nice stuff to say about the newsletter.

Praise for the Design Newsletter

Thank you for your newsletter. It’s possibly the best newsletter I’ve received since 1999, when I started freelancing.

Tricia Littlefield
Founder, TheSimpleWeb

Each time I receive an email from you, I’m like ‘Damn, this is a long email! No way will I read all of this’, then I began to read and I’m like ‘Damn, this is so freaking brillant’ and read it all.

Jean-Philippe
UX Strategist, Freelance

Over 30,000 subscribed.
No spam. Unsubscribe anytime.



Source link

A Guide to Console Commands
Strategy

A Guide to Console Commands


The developer’s debugging console has been available in one form or another in web browsers for many years. Starting out as a means for errors to be reported to the developer, its capabilities have increased in many ways; such as automatically logging information like network requests, network responses, security errors or warnings.

There is also a way for a website’s JavaScript to trigger various commands that output to the console for debugging purposes. These commands are contained in a console object available in almost every browser. Even though these features are mostly consistent between browsers, there are a few differences. Some of these differences are simply visual in nature while others do have slight functional differences to keep in mind.

For the curious, here’s the spec by WHATWG linked from the MDN console docs.

This guide covers what’s available in the console object of Firefox and Chrome as they are often the most popular browsers for development and they do have a few differences in various aspects of the console. The new Chromium-based Edge is essentially the same as Chrome in many ways so, in most cases, the console commands will operate much the same.

Quick Links

The console.log command

The first thing we can do is log the console object itself to see what your browser of choice actually offers.

console.log(console);

This command will output the various properties of the console object as the browser knows them. Most of them are functions and will be rather consistent regardless of browser. If there are differences in the properties of the console object from one browser to another, this way you can see the differences. One such difference I can point out between Firefox and Chrome is that Chrome provides a “memory” property that outputs some basic memory usage stats. Firefox doesn’t provide this property and yet has a “name” property that Chrome does not have.

Thankfully, most of the differences between the browsers tend to be just as trivial. That way, you can be fairly confident that your code will output much the same regardless of the browser in use.

First things first: clear()

With heavy usage of the console comes a very crowded output of text. Sometimes you just want to clear things out and start with a fresh console. Browsers typically provide a button in DevTools that performs this task. However, the console object itself also provides a command to handle this:

console.clear();

This will clear the console and will helpfully inform you of that by outputting a message like “Console was cleared.”

Common usage: debug(), error(), info(), log(), and warn()

There are five commands that at first glance seem to do the exact same thing. And, technically, they do. But browsers provide additional features tied to the five commands to give each their own distinct benefit.

These five commands are:

console.debug();
console.error();
console.info();
console.log();
console.warn();

I’m sure many of you have seen console.log() before (I mean, we just talked about it up top) and have probably used it before. Before we get into what you can log in these five commands, let’s see our first minor difference between Chrome and Firefox.

Chrome console showing debug, error, info, log, and warn

This is an example in Chrome of each command outputting a string, such as console.debug('console.debug()');.  Notice that some of them have a color treatment to give a visual indication of the type of output it is. The error and warn outputs have an additional icon for even easier identification.

Firefox console showing debug, error, info, log, and warn

Here is the same list in Firefox and, while it looks similar, there are three minor differences. For example, console.debug() is not color-coded and console.info() has an additional icon next to it. In Chrome, both console.error() and console.warn() can be expanded to show additional information about the output while Firefox only does this with console.error(). This additional information provides a trace of the lines of code involved to get to where the particular command was called.

One thing that is useful about these five commands is that the browsers provide filtering options to show or hide each type as you wish. Firefox has them right there at the top of the console above the output while Chrome hides them in a dropdown, labeled “All levels” which you can see in the earlier Chrome console screenshot. “All levels” is there because I have all five set to be shown. If you were to choose the “Default” option then the debug output (listed as “Verbose”) is hidden while the others are shown. Unchecking “Info”, “Warnings”, or “Errors” causes the dropdown to display a different title such as “Custom levels” or “Errors only” depending on what is selected.

The intentions for usage of error and warn are easy to determine; how to use the other choices is up to you. If you do make extensive use of the different options then you might consider documenting the expectations of each as to not confuse things late in the project — especially if it is a team project.

Now, let’s discuss what we can actually log inside these commands. Since they all behave the same, I’ll just focus on logging as the example.

The simplest examples involve just passing a string, number, object, or array into the log command. Technically, any of JavaScript’s data types can be used, but for most of them, the output is much the same.

console.log('string');
console.log(42);
console.log({object: 'object'});
console.log(['array', 'array']);
Chrome string, number, object, and array log examples

I’m showing these examples in Chrome with the object and array already expanded. They are normally collapsed but the output next to the arrow is consistent between both states. Firefox displays a little differently but, for the most part, the output is the same. Firefox does tell you whether it is displaying an object or array before expanding, but shows the same as Chrome while expanded.

One interesting thing to add is that you can pass more than one item to the log as parameters and it’ll display them inline.

console.log('string', 'string');
console.log(42, 1138);
console.log({object: 'object'}, {object: 'object'});
console.log(['array', 'array'], ['array', 'array']);
Chrome strings, numbers, objects, and arrays examples

Often when I’m working with x and y coordinates, such as what can be outputted by mouse events, it’s useful to log the two together in one statement.

String substitution

The different console logging commands provide string substitution that allows inserting different values into the string for output. This is useful for describing a variable in the log to make it clear as to what’s being reported.

console.log('This is a string: %s', 'string');
console.log('This is a number: %i', 42);
console.log('This is an object: %o', {object: 'object'});
Chrome string substitution examples

Here is a list of the data types that can substituted into the output string:

Data type Substitution symbol
Objects and arrays %o or %O
Integers %d or %i
Strings %s
Floats %f

The first parameter would be the string to output with the symbols placed in the appropriate locations. Then each parameter after that is the value to substitute inside the first parameter’s string. Keep in mind that you’ll have to keep the substitution types and the parameters in the specific order or you’ll get unexpected results.

If your console supports template literals, it’s a bit easier to get similar results as string substitutions.

console.log(`This is a string: ${'string'}`);
console.log(`This is a number: ${42}`);
console.log(`This is an object: ${{object: 'object'}}`);
Chrome template literal examples

Notice that the object is handled a bit better with the string substitution, so pick the appropriate choice for your requirements. Since it’s possible to insert more than one value in the output, let’s compare the two.

console.log('This is a string: %s. This is a number: %i', 'string', 42);
console.log(`This is a string: ${'string'}. This is a number: ${42}`);
Chrome string substitution and template literals

With the string substitution each value is added as a parameter to be inserted into the output. With template literals, on the other hand, you add them wherever they need to be in the output. Also, you can combine them.

console.log(`This is a number: ${42}. This is an object: %o`, {object: 'object'});
Chrome string substitution with template literals

So, there are lots of options to pick and choose from so you can go with the best options for your needs. 

Styling the output

Another potentially useful and fun thing is that you can apply CSS styles to the console’s output. It works just like the string substitution method where you insert a %c variable for styles to be applied from the parameters.

Here’s a simple example:

console.log('%cThis is large red text', 'color: red; font-size: 30px;');
Chrome styling in the console

This time there is a slight difference in the Firefox output:

Firefox styling in the console

Not really that much of a difference, but something to keep in mind.

What essentially happens is that %c reads the strings in the parameters to determine what styling to apply. So, say there’s a second styling being passed, %c moves on to the next parameter, much like with string substitution. An empty string in the parameter list resets the styling back to default.

console.log('This is %cred text %cand this is %cgreen text.', 'color: red;', '', 'color: green;');
Using multiple styles in the Chrome console.

The styling properties available are rather limited when compared to typical CSS styling on a webpage. You can look at it as a sort of inline block of text that allow you to manipulate a limited set of styling properties.

With some work and experimenting, you could create interesting messaging within the console. One idea is to draw extra attention to a particular log, especially an error of some sort.

console.log('%cHello there!', `
  background: white;
  border: 3px solid red;
  color: red;
  font-size: 50px;
  margin: 40px;
  padding: 20px;
`);
Chrome custom styling

In this example, we can see that the CSS is a bit verbose, but there is something we can do to mimic the class system that we leverage in CSS. The values of each parameter for styling can be stored in variables to allow for repeated use without having to duplicate the string of styles in each parameter.

const clearStyles = '';
const largeText = 'font-size: 20px;';
const yellowText = 'color: yellow;';
const largeRedText = 'font-size: 20px; color: red;';
const largeGreenText = 'font-size: 20px; color: green;';


console.log(`This is %clarge red text.
%cThis is %clarge green text.
%cThis is %clarge yellow text.`,
  largeRedText,
  clearStyles,
  largeGreenText,
  clearStyles,
  largeText + yellowText
);
Chrome custom template styling

There are several things going on here, so let’s break it down a bit. First, we have a collection of variables that holds our styling strings. Think of each as a sort of class to be reused in the parameters of the console log.

We are also using a template literal in the log, which means we can have line breaks in our output. Then, for each %c in the text, there’s a corresponding variable used in a parameter to define the styles for that particular part of the output text. In addition to each variable that holds styling, there is also a clearStyles argument that can be used to reset styles to prepare for the next set of styling. You could just use an empty string as in previous examples, but I like the clear intention that comes from using the variable name. The last parameter shows that the variables can be combined, which opens up more possible ways of handling the styles.

Now, that’s a great deal of text covering essentially five console commands that only output text to the console. So, let’s move on to other commands of the console object. Although, some of these can still use many of the features described so far, we won’t focus on that aspect as much with the following commands.

Being assertive: assert()

The console.assert() command is similar to the error command mentioned previously. The difference is that asserting allows for the usage of a boolean condition to determine whether it should output the text to the console.

For example, let’s say you wanted to test the value of a variable and make sure it wasn’t larger than a certain number value. If the variable is below that number and the condition resolves to true, the assert command does nothing. If the condition resolves to false, then the output text is displayed. This way you don’t have to wrap a console.error() command with an if statement to determine if the error message is needed in the first place.

let value = 10;
console.assert(value <= 7, 'The value is greater than 7.');
Chrome assert example

We can see that assert has the same appearance as the error command, except that it also prepends “Assertion failed:” to the output text. Chrome can also expand this output to show a trace of where the assertion came from.

The trace can be quite helpful with common patterns of functions within functions calling other functions and so on. Although, you can see in the example above that the line the assert came from doesn’t tell you how the code got to that line.

let value = 10;


function function_one () {
  function_two();
}


function function_two () {
  function_three();
}


function function_three() {
  console.assert(value < 7, 'This was false.');
}


function_one();
Chrome assert with trace

This sequence is actually in reverse order in terms of the code. The last line shows an anonymous entry (which is an HTML script tag in this case) on line 78. That’s where function_one was called. Inside that function, we have a call for function_two, which, in turn, calls function_three. Inside that last function is where the assert is located. So, in this development world of functions sharing other functions; a description of the path to that point of the assert is quite handy.

Unfortunately, this trace is not provided in Firefox with the assert command, as it is with the error command.

Firefox assert example

Keeping count: count() and countReset()

Ever wonder how many times a certain thing happens in your code? For instance, how many times does a particular function get called during a sequence of events? That’s where the console.count() command can help out.

By itself, the count command is rather simple and has limited use. If you use the command in its default state you only get a simple count. For example, if we call it three times in a row, we get a sequential count.

console.count();
console.count();
console.count();
Chrome default count example

As you can see, we get a simple count from one to three. The default behavior means that count is merely incrementing the output by one each time it runs, no matter where it shows up in the code. You do get the line number in the code where it happened, but the count is a simple total no matter the situation.

To make this command a bit more useful, we can provide a label to keep a separate count for that label.

console.count('label A');
console.count('label B');
console.count('label A');
console.count('label B');
console.count('label A');
console.count('label B');
Chrome label count example

Even though using the count command with labels causes the output to alternate between labels, each one keeps its own count. One scenario where this comes in handy is placing a count inside a function so that every time that function is called, the count is incremented. The label option makes it so that a count can be kept for individual functions to provide for a good idea of how many times each function is being called. That’s great for troubleshooting performance bottlenecks or simply seeing how much work a page is doing.

There’s a way to reset the count. Let’s say we have a loop that gets called multiple times, but the number of iterations of the loop can be dynamic. This is done with the console.countReset() command with the same label from the count command.

console.count();
console.count();
console.countReset();
console.count();


console.count('this is a label');
console.count('this is a label');
console.countReset('this is a label');
console.count('this is a label');
Chrome count reset example

Each count — with and without a label — is called twice and console.countReset() is applied right before another count instance. You can see that Chrome counts up to two, then restarts when it encounters countReset. There’s nothing in DevTools to indicate the reset happened, so an assumption is made that it did happen because the count started over.

And yet, the same code is a bit different in Firefox.

Firefox count reset example

Here, the reset is indicated by the count being set all the way back to zero. That is the indicator that the reset was called, whereas we have no such indication in Chrome.

As for label options, just about anything can be used. I suppose a simple way to describe it is that if you give it anything that can be resolved to a string, it’ll probably work as a label. You could even use a variable that has values that change over time, where count will use the current value of the variable as a label each time it is encountered. So, you could keep count of the values as they change over time.

Describe that thing: dir() and dirxml()

The main idea behind these two commands is to display either properties of a Javascript object with console.dir() or descendant elements of an XML/HTML element with console.dirxml(). It appears Chrome has these implemented as expected, while Firefox just uses both as aliases for console.log().

Let’s give console.log(), console.dir(), and console.dirxml() the same simple object to see what we get. Keep in mind that you normally would not log an object with console.dirxml().

const count = {
  one: 'one',
  two: 'two',
  three: 'three'
};


console.log(count);
console.dir(count);
console.dirxml(count);
Chrome simple dir() and dirxml() example

Firefox gives us much the same, except the console.dir() is automatically expanded.

Firefox simple dir() and dirxml() example

Another simple comparison to console.log() is to repeat the object in the same command.

Chrome dir() and dirxml() double example
Firefox dir() and dirxml() double example

Not really that much different other than that Chrome doesn’t show the second object in console.dir() like Firefox does. Which makes sense because Chrome is trying to display properties of an object (ignoring the second) while Firefox is just aliasing everything to a console.log(). So, for situations like this with objects there is little difference between console.log(), console.dir(), and console.dirxml() in the browsers.

A useful benefit of console.dir() in Chrome that I can point out is how DOM elements are handled. For example, here’s how console.log() displays in Chrome and Firefox when given a DOM element.

Chrome console.log() DOM example.
Firefox console.log() DOM example

Now, I’ve always liked how Firefox outputs a DOM element inside a console.log(), as it gives you all the properties of that DOM element. So, when I wanted to look up a specific property of a DOM element to manipulate with JavaScript, it’s only a console.log() away to find it. Chrome, on the other hand, gives us the HTML code of the DOM element in the console.log() just like it would in console.dirxml().

To get the properties in Chrome, use console.dir() with the DOM element. I was quite happy to find that console.dir() in Chrome provides the properties of a DOM element just as I came to rely on that information in Firefox.

As for console.dirxml() in Chrome, it can be useful for displaying an HTML element and its children outside of the clutter of the DOM Inspector. You can even edit some of the existing HTML live in the console, but you won’t have the same level of abilities as in the DOM Inspector.

Let’s get together: group(), groupCollapsed(), and groupEnd()

Here’s a simple one: Group different console outputs together to show a form of relationship among them. It is somewhat limited in features so its usefulness will depend a great deal on how you plan to use it. This is the console.group() command.

console.group();
console.log('one');
console.log('two');
console.log('three');
console.groupEnd();


console.group('this is a label');
console.log('one');
console.log('two');
console.log('three');
console.groupEnd();
Chrome group() example

In the first block of code we call console.group() in its default state, have three logs, and then finally call console.groupEnd(). The console.groupEnd() simply defines the end of the grouping. The second block has a string as a parameter that essentially becomes the label for that group. Notice that in the first block without a label it just identifies itself as a console.group in Chrome while in Firefox it shows as <no group label>. In most cases, you’ll want a proper label to distinguish between groups.

Also notice the arrow next to the labels. Clicking on that collapses the group. In the code examples above, if we change console.group() to console.groupCollapsed(), they start collapsed and must be opened to see the output.

You can also nest the groups. The console.groupEnd() command simply refers to the last opened group.

console.group('outer group');
console.log('outer one');
console.log('outer two');
console.group('inner group');
console.log('inner one');
console.log('inner two');
console.log('inner three');
console.groupEnd();
console.log('outer three');
console.groupEnd();
Chrome nested group() example

Just as a quick note, if you want the group label to stand out a bit more in a list of output in the console, you can style it just as we did with strings earlier.

console.group('%cstyled group', 'font-size: 20px; color: red;');
console.log('one');
console.log('two');
console.log('three');
console.groupEnd();
Chrome styled group() example

Have a seat at the: table()

In previous examples, we’ve seen what happens when we put an array or object inside a console.log() or console.dir(). There’s another option for these data types for a more structured display, which is console.table().

Here’s a simple example with an array:

let basicArray = [
  'one',
  'two',
  'three'
];
console.table(basicArray);
Chrome basic array table() example

Here’s the same example in Firefox for comparison.

Firefox basic array table() example

A slight visual difference, but pretty much the same. That said, Chrome does still give you the expandable output under the table, much like you’d see in console.log(). Chrome will also provide basic column sorting if you click on the heading.

The output is similar when passing in an object:

let basicObject = {
  one: 'one',
  two: 'two',
  three: 'three'
};
console.table(basicObject);
Chrome basic object table() example

So, that was a pretty simple example with basic outputs. How about something a little more complex and is often used in coding projects? Let’s look at an array of objects.

let arrayOfObjects = [
  {
    one: 'one',
    two: 'two',
    three: 'three'
  },
  {
    one: 'one',
    two: 'two',
    three: 'three'
  },
  {
    one: 'one',
    two: 'two',
    three: 'three'
  }
];
console.table(arrayOfObjects);
Chrome array of objects table() example

As you can see, this gets us a nice layout of objects with repeating keys as column labels. Imagine data along the lines of user information, dates, or whatever might be data often used in loops. Keep in mind that all the keys in each of the objects will be represented as a column, whether there is corresponding keys with data in the other objects. If an object doesn’t have data for a key’s column, it appears as empty.

An array of arrays is similar to the array of objects. Instead of keys being labels for the columns, it uses the index of the inner arrays as column labels. So if an array has more items than the other arrays, then there will be blank items in the table for those columns. Just like with the array of objects.

So far, simple arrays and objects have simple output displayed. Even a slightly more complex array of objects still has a solid, useful structure. Things can get a bit different with mixing the data types though.

For example, an array of arrays where one of the inner array items is an object.

let arrayOfArraysWithObject = [
  ['one', 'two', {three: 'three', four: 'four'}],
  ['one', 'two', {three: 'three', four: 'four'}],
  ['one', 'two', {three: 'three', four: 'four'}]
];

console.table(arrayOfArraysWithObject);
Chrome array of arrays with object table() example

Now, to see what is contained in those objects in the third column, we’ll have to expand that array output below the table. Not that bad, really. Here’s how Firefox handles the same output.

Firefox array of array with object table() example

Firefox just lets us expand the object within the table.

How about mixing the data types the other way, where we have an object with arrays as values for each key? It works much the same as the array of arrays. The difference is that each row is labeled with a key instead of the index. Of course, for each level of data type you add to the mix will result in a more complex looking table. 

This is all about: time(), timeLog(), and timeEnd()

Here we have a simple way to log how long something takes to complete. We call console.time() with a label, call console.timeLog() with the same label for an update, and call console.timeEnd() again with the same label to stop the timer.

console.time('this is a timer');
console.timeLog('this is a timer');
console.timeEnd('this is a timer');

The output for Chrome and Firefox is much the same. Here’s an example output with code that logs the time every second for five seconds and then stops.

Chrome time() example
Firefox time() example

Notice that the reported times are not quite the same, but probably close enough for most requirements. Also, Firefox is nice enough to note that the timer has ended while Chrome requires an assumption once the label stops appearing. The first four lines of output come from the call console.timeLog('this is a timer'); and the last line is from the call to console.timeEnd('this is a timer');.

Dropping breadcrumbs with: trace()

The console.trace() command is actually similar to console.error() and console.warn(). Calling this command will output a stack trace to the console showing the path through the code to that call. We can even pass it a string as a form of label, but other data types such as arrays or objects can be passed. The behavior of passing data like that is the same as what we would get from a console.log() call. It’s a simple way to pass along some information to the console without triggering a more dire looking console.error() or console.warn() call.

debugger

This is a simple command to trigger a pause in the console’s debugger, if it exists. It is similar to placing a breakpoint in the debugger, or the browser’s equivalent, to cause the same type of pause while executing code. Here’s a simple example:

function whatsInHere() {
  debugger;
  // rest of the code
}

In this particular example, the open console’s debugger will pause code execution and the browser will open up the source file to show the line of code as soon as the function is called. It could be useful for easy breakpoints with some complicated projects.

Technically, the debugger command isn’t a part of the console object in the browser. It’s a useful feature that the console will respond to from JavaScript code.

Some additional console utilities

That’s a good look at most of the standard commands available to us in the console object. Each of these will work more-or-less the same across modern browsers. There may be some differences between browsers, as we saw in some of the examples. But there are a few more things I’d like to take a moment to point out, as they might prove useful in various ways.

The following examples can be considered more like console “utilities.” They are not a part of the console object like most of the previous examples. Therefore they are not called with a leading console object reference. These utilities are supported directly by the browsers themselves. They cannot be called from JavaScript code but must be typed directly in the console to be used. In some cases the utility might be unique to a particular browser, in others the utility is supported much the same way in several browsers. Your mileage may vary based on your browser of choice.

$0, $1, $2, $3, $4

These five commands are extremely handy. The first one, $0, represents the currently selected element in the DOM inspector. This essentially provides a shortcut instead of having to use more traditional DOM methods, such as getElementById or a querySelector. You can use it in various ways, within various console commands, or by itself to get information about the currently selected element. For example:

console.log($0);

The other commands in this set represent elements that were previously selected. Think of them as a form of selection history. $1 is the previous element, $2 is the previous before that, and so on. Although the first command is available in Firefox, the commands for previously selected elements are not.

$(‘element’), $$(‘elements’)

If you find yourself typing out document.querySelector('element') in the console repeatedly, there’s a shortcut. You can just type $('element') and it performs the same function. The shortcut might remind many of jQuery, but to select multiple elements reminds me of MooTools. To select multiple elements, you’d use $$('elements') instead of document.querySelectorAll('elements').

$x(‘//element’)

This is a shortcut for XPath that will return an array of elements that match the expression. An easy example is $x('//div'), which will present an array of every div element on the page. This isn’t that much different than using $$('div') like we did with $('element'), but there are many options for writing XPath expressions.

One example of a simple step up in a XPath expression is $x('//div[span]'), which would return the div elements on the page that happen to contain a span element. This is the equivalent of :has in CSS Selectors Level 4 draft, which isn’t supported in browsers yet.

These are just basic examples that only scratch the surface of XPath.

clear()

This is another version of console.clear(), but without the “Console was cleared” message.

getEventListeners(object)

This command, when given a DOM element, will report the event listeners registered to that element. For example, using the $0 example from above we can use getEventListeners($0) to get something like this:

Chrome getEventListeners() example

Expanding each item in the array provides various information about that event listener. This function isn’t supported in Firefox, but it does offer something similar that can be found in the DOM inspector.

Firefox DOM Inspector events information.

Clicking on the “event” badge next to the element provides a list of events registered to the element. Then each event can be expanded to show the code involved with the event.

That’s it for now!

 I’ll end it here, with a large amount of information detailing various commands that can be used in the browser’s console output or with JavaScript. This isn’t everything that is possible — there’s simply too much to cover. In some cases, each browser has its own capabilities or utilities that can be leveraged. We looked at the bulk of what we might find in Chrome and Firefox, but there’s likely more out there. Plus, there will always be new features introduced in the future. I invite you to dig deeper to discover more ways to leverage browser DevTools for your coding projects.



Source link