JavaScript is one of the most powerful language in this modern world. In this article we will go through some of the useful JavaScript one-liners.
- If you want to get the text that a user selects or highlights on a web page, there is a useful one-liner for that.
const getSelectedText = () => window.getSelection().toString();
console.log(getSelectedText);
- There is a method called
scrollTo(x,y)
, it allows you to scroll to a particular set of used coordinates.
const scrollToTop = () => window.scrollTo(0,0);
- If you want to have a smooth scrolling animation, just do something like this:
const Top = () => window.scrollTo({top:0, behavior: 'smooth'});
- Internet bandwidth is basically the amount of data is being transferred over an internet connection in a specified period of time.
navigator.connection.downlink;
- If you want to redirect user to a specified location, you can do something like this:
const urlRedirect = url => location.href = url;
urlRedirect('https://dev.to/');
Hope you'll find some useful snippets in this code. Comment if you have more other than these.
You may also like to read: Killer JavaScript One Liners
Happy Coding Devs.
Top comments (10)
Small typo in your smooth scrolling example, missing
'
at the end of smooth. Instead of your urlRedirect function, you can directly calllocation.assign(url)
.Thank you, for pointing my mistake. And yes we can use
location.assign(url)
aswell.A bit of background to this redirection thingy.
If you use location without specifying to which API you are referring to if could apply either to document or window.
Both usually work the same as most modern browsers map
document.location
towindow.location
and also some replaceddocument.location
todocument.URL
to avoid confustion.Still
window.location
is the canonical way (recommended).Setting the value of href creates effectively a navigation which will be in the
window.history
, if you want to avoid this, you can usewindow.location.replace()
or, if you want to modify the current URI to, let's say, delete the query string but without reloading, you can use thewindow.history
API instead.Sorry for not adding the references, I'm on the phone right now but you can probably find all this info inside mdn. 😁
Hi,
navigator.connection.downlink;
is useful if you are not using Firefox or Safari (see can I use)thanks for updating.
very nice!🌹
Nice one. thanks
Simple and useful. Thanks for sharing.
awesome snippets!
I was wondering if these snippets can be used in all browsers and not just a selected few? Asking for a friend.
Thanks for sharing. Very useful for me that you shared informations.