DEV Community

Cover image for 6 useful frontend techniques that you may not know about
Matvey Romanov
Matvey Romanov

Posted on • Updated on

6 useful frontend techniques that you may not know about

A small selection of little-known techniques for HTML, CSS, and JavaScript.

The frontend is the first line of defense of the website (or, more precisely, the first line of "attack" on the user), so front-end developers always have a lot of work to do. To make their lives a little easier, we've picked up some useful, but not very well-known HTML, CSS, and JavaScript techniques.

1. Quickly hide

To hide a DOM element, you don't need JavaScript. A native HTML attribute is enough hidden. The effect is similar to adding a style display: none;. The element simply disappears from the page.

<p hidden>This paragraph is not visible on the page, it is hidden from the HTML.</p>
Enter fullscreen mode Exit fullscreen mode

Of course, this trick won't work with pseudo-elements.

2. Position quickly

Are you familiar with the inset CSS property? This is an abbreviated version for the familiar top, left, right and bottom. By analogy with the short syntax margin of the or property padding, you can set all offsets for an element in one line.

// Before
div {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

// After
div {
  position: absolute;
  inset: 0;
}
Enter fullscreen mode Exit fullscreen mode

Using a short syntax is useful for reducing the size of the CSS file, and the code looks cleaner this way. However, don't forget that inset is a boolean property, it takes into account the email direction. In other words, if your site uses a language with the rtl direction, then left will turn out to be right and vice versa.

3. Find out your internet speed

You can easily determine the user's internet speed from JavaScript code using an object navigator.

navigator.connection.downlink;
Enter fullscreen mode Exit fullscreen mode

This is currently an experimental technology, although it is supported by a number of popular browsers, so be careful with it.

4. Enable vibration on your smartphone

Yes, this is also possible. The object's vibrate() method window.navigator can enable vibration mode on a mobile device.

window.navigator.vibrate(500);
Enter fullscreen mode Exit fullscreen mode

You can pass the parameter vibration time in milliseconds to the method. Or you can even specify a pattern-the alternation of vibration intervals and pauses. To do this, pass the method an array of numbers.

5. Prohibit pull-to-refresh

Pull-to-refresh is a popular mobile development pattern. If you don't like it, just disable this effect using the overscroll-behavior-y CSS property with the value contain.

body {
 overscroll-behavior-y: contain;
}
Enter fullscreen mode Exit fullscreen mode

This property is also very useful for organizing scrolling inside modal windows – it prevents the main page from intercepting scrolling when it reaches the border.

6. Prohibit inserting text

You may want to prevent the user from pasting text copied from somewhere in the input fields (think carefully about whether it's worth it). This is very easy to do by tracking the event paste and calling its method preventDefault().

<input type="text"></input>
<script>
  const input = document.querySelector('input');

  input.addEventListener("paste", function(e){
    e.preventDefault()
  })

</script>
Enter fullscreen mode Exit fullscreen mode

Oops, now you won't be able to copy-paste, you'll have to write and enter everything by hand.

These techniques are not used very often, but they can be useful in a number of situations. I hope you found something interesting for yourself.

Top comments (51)

Collapse
 
grahamthedev profile image
GrahamTheDev • Edited

There is a special circle in hell for people who disable paste.

A massive security issue as it makes people choose simpler passwords etc. and an even bigger accessibility issue as people with cognitive disabilities may rely on copy and pasting information to fill out forms, authentication etc.

Luckily WCAG 2.2 addresses this fact so it will now mean your site is not WCAG compliant and therefore illegal in about 80% of countries.

w3.org/WAI/WCAG22/Understanding/ac...

So don't fucking do it on inputs or at all preferably.

Oh and while navigator.connection.downlink; is hopefully going to be useful one day, at the moment it is so unreliable (even if "supported" it doesn't actually report accurate results) you can't use it if you actually want to make decisions based upon it.

So 4.5 useful tip and 1 terrible idea! 😋🤣

Either way though the other tips are well worth a ❤ and a 🦄!

p.s. inset is only 82% coverage on browsers so you will want to polyfill it if you use it on anything important and overscroll-behavior-y doesn't work on iPhone (Google or Safari) and only has 75% coverage so you can't really rely on that either, not sure if a polyfill exists for that - still useful things to know but don't just use them blindly.

Collapse
 
drumstix42 profile image
Mark

There's at least some valid cases but they are very specific.

For example: a student test/exam where the page doesn't want answers copy & pasted.

Collapse
 
grahamthedev profile image
GrahamTheDev • Edited

I still don't think that would be a valid case, but I can understand why you and José (comment further down) have said that.

For example: what exam could you possibly be taking where copy and pasting an answer would actually be a thing or be useful to you as a student trying to cheat?

If you did that it would just be plagiarising and you would be marked down anyway.

Plus if you were cheating you could just rewrite the answer, I doubt anyone would copy a whole book into an online exam so it would be pretty straight forward to copy an answer by just typing it in manually in so all you did was slow them down a little bit.

Now if someone was dyslexic and liked to use a Word Processor to write in a font that makes it easier for them to read, or adjust the line length so they don't lose their place (as long line lengths can be difficult for certain types of dyslexia), you need copy and paste.

There are other things to consider such as people with poor vision may find it a lot easier to write in a certain program that is already set to their font size and contrast requirements and copy and paste in etc.

The road to hell is paved with good intentions like disabling paste to try and stop cheating, it won't work but it will mean that somebody who isn't cheating will suffer.

do not disable copy and paste, it is that simple. I wouldn't normally be so forceful but people try and justify terrible practices and may read your comment thinking "oh yeah, that is a good idea", without thinking about the consequences (or whether it would actually be effective).

Collapse
 
ogrotten profile image
ogrotten

That's not a web problem, it's a "test moderation" problem. There's plenty of other ways to detect or especially prevent cheating.

Collapse
 
leob profile image
leob

One really (but I mean REALLY) cool tip - the hidden attribute ... that one alone makes this post worthwhile, even when I don't really care about the rest ... oh and yes disabling copy/paste sounds like the worst idea ever, I can't come up with any use case where it would make sense ...

Collapse
 
itshi32 profile image
itshi

Why hidden is better than .some{display:none} ?

Thread Thread
 
grahamthedev profile image
GrahamTheDev

Because if you build a component you can just use it in another project without worrying about styling being included.

Also just so you know, it is a good practice to still add [hidden]{display:none!important} to account for older browsers and some obscure browsers. And yes, although most of the time !important is bad, if something is hidden then you want to override any other styling.

Another benefit is if for any reason your CSS fails (as failed network requests do happen) then the item is still hidden.

And one last benefit is maintainability, if you have a team you start getting .invisible, .hidden, .dontshow, .hide etc. If you tell the team to just add the hidden attribute they never had to worry about it again.

Oh and I suppose the fact that hidden on the element means that you don't need .hidden or equivalent in your CSS when it comes to critical rendering and performance. Super tiny difference but lots of little things likes this really add up!

I hope that helps (I might even write a post on it as there are actually more benefits than I thought!)

Thread Thread
 
leob profile image
leob

It isn't better, it just surprises me that there are features like this that I had no clue even existed. But yeah it's not earth shattering, it's more a piece of trivia.

Collapse
 
theanonymouskoder profile image
The Anonymous Koder

I agree that this is horrible for authentication but can be used to do other things. For example, some educational institutes prevent this (when the user has to type essays and stuff) because typing helps you remember concepts better. And this can also be used as an extra safety layer in cheat prevention systems (in online examination systems).

Collapse
 
hyggedev profile image
Chris Hansen

Im dead! Lol 💯 🤣

Collapse
 
snickdx profile image
Nicholas Mendez

Great post! I cannot think of any use case for disabling pasting other than annoying the user 😆.

Collapse
 
bherrero profile image
Borja Herrero

It's annoying indeed. I've seen it in a form where the user had to put their email twice in order to verify it. So it was twice as annoying as both fields had paste disabled.

Collapse
 
jfullerco profile image
jfullerco

The perfect way to ensure you enter your email incorrectly… twice…

Collapse
 
webdev710 profile image
webdev-710

I think it will come in handy later. I will make a note of it :)

Collapse
 
theanonymouskoder profile image
The Anonymous Koder

Typing helps reinforcing concepts so it can be used in educational institutes and also in cheat prevention systems in online examinations.

Collapse
 
elabftw profile image
eLabFTW • Edited

Can't believe I didn't know about the "hidden" attribute!!! BTW, don't forget to add aria-hidden=true for accessibility ;)

Collapse
 
ashleyjsheridan profile image
Ashley Sheridan

Actually, the hidden attribute is a lot less useful than it initially seems. It has a lower order of priority, so any CSS rules which change the display of an element will be able to completely override it. For example:

<div hidden style="display: block;">I am not a hidden element!</div>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
escornwell profile image
Eric Cornwell

This bit me this week. Changed a div to a font awesome icon, but the fa class overrode the hidden attribute, so the new icon was unexpectedly always visible.

Thread Thread
 
ashleyjsheridan profile image
Ashley Sheridan

You will likely improve the accessibility of that icon considerably if you use an inline SVG, although not knowing your exact situation, I can't say that with absolute certainty. Font icons typically don't play nicely with screen readers or Braille browsers, so that icon becomes effectively non-existent for people relying on that technology to browse the Web.

Thread Thread
 
paulsmithkc profile image
Paul Smith • Edited

From an accessibility context, you can generally add a label to the control in any variety of ways, and show that instead of an icon. Which how I generally use fontawesome.

<button title="GitHub"><i class="fab fa-github"></i></button>

This gives the button a tooltip, which screen readers can read instead.

<button><i class="fab fa-github"></i><span class="visually-hidden">GitHub</span></button>

Or a "hidden" span using Bootstrap 5's utility classes.

Thread Thread
 
ashleyjsheridan profile image
Ashley Sheridan

Not all screen readers will read out title attributes, so you shouldn't be relying on that. You can use ARIA attributes instead, but therse should be used as a last resort.

Also, inlining and SVG can be useful to avoid extra HTTP requests, all of which have a negative impact on the performance of the page, especially if the user is on a slow or metered connection (which is most of the world, including a lot of the USA). Again, I'm not saying always do this, but it can be used as part of an overall strategy.

Probably not necessary to include the whole of Bootstrap for what is effectively a 4-5 lines of CSS to set an item to be visually hidden but available to screen readers as well, that will be another performance hit.

Even if you can't inline the SVG, you can make it a background image and add it in as a data URL in the CSS. For icons this is generally fine, as icons are very simple, so the data URL is actually quite small. It's often more performant to do this than have the CSS reference external image files.

Thread Thread
 
paulsmithkc profile image
Paul Smith • Edited

Good point on the title attribute.

I'm already using Bootstrap for many other things, when it comes to this. Plus I already compile the parts I need with SASS, and minify the whole thing with Webpack. So it's actually not that much of an issue.

Font-awesome is much smarter than it used to be. The npm/webpack version allows you to pick and choose which icons you need, so you don't have to ship the whole icon pack.

Thread Thread
 
ashleyjsheridan profile image
Ashley Sheridan

The size of the request isn't the only issue. The whole HTTP request has a connection negotiation step before content is transferred which also takes time. On a slow connection (such as dialup or a lot of lower end mobile phone plans) or on one with high latency (for example, satellite connection where upstream requests are done via dialup). The number of extra HTTP requests is a big drain on performance, and ultimately that affects the accessibility of the content too.

Try testing your site/webapp out on a browser with a throttled connection and see how well it performs. You'll see that it's those extra requests which can really have the biggest impact. And when content isn't loaded by a specific time, you can run into all kinds of issues with document reflow, hidden or missing content, and in the worse case, errors caused by code which expects the content to already be there.

I'm not trying to crap all over things like Bootstrap or Font-awesome, but I'm saying it helps to be aware of the issues they can cause and not just the issues they solve.

Collapse
 
jordanfinners profile image
Jordan Finneran • Edited

It's actually recommended not to do this. Using the HTML hidden attribute will do this for you, which is the benefit of using HTML
developer.mozilla.org/en-US/docs/W...

Collapse
 
elabftw profile image
eLabFTW

You're correct, I thought about it after! And it would be silly to do that in that case. Cheers :)

Collapse
 
riobrewster profile image
RioBrewster

What's the use case for this? The current trend with accessibility is to never hide anything from a screen reader. Is it just an easier hook for javascript?

Collapse
 
joseme profile image
José Torres

Paste disable could be useful for test input, to avoid cheating.

Collapse
 
natalia_asteria profile image
Natalia Asteria

But not good for students with dyslexia, as @inhuofficial said here.

Collapse
 
manuelricci profile image
Manuel Ricci

I was unaware of overscroll-behavior-y: contain; thanks!

Collapse
 
escornwell profile image
Eric Cornwell • Edited

About inset you say "inset is a boolean property, it takes into account the email direction". I think you mean it's a logical property, and it respects the flow direction. Following the link you provided to the Mozilla docs, there is no mention of booleans or email.

Collapse
 
aheisleycook profile image
privatecloudev

good poiny

Collapse
 
tlcheung profile image
TL Cheung

Does anyone know an HTML attribute for tool tips? I swear I read one of these articles that showed a very simple way to do it. But know I want to use this feature and all I can find are very long & involved html/css. I love css and wouldn't mind if it was only a few lines of code but I don't want something very complicated.. Thanks

Collapse
 
meo3w profile image
Phil Hasenkamp

Very awesome! Thank you for sharing your knowledge!

Collapse
 
ra1nbow1 profile image
Matvey Romanov

Thank you so much

Collapse
 
talorlanczyk profile image
TalOrlanczyk

Hi great stuff
But I would recommend adding that while using the hidden feature you cant do animation on it .
You have to add className any way

Collapse
 
reza profile image
Reza Majidi

Interesting. thanks 🙏