I love JavaScript because it's full of surprises and is used for so many amazing things.
Many developers love it, and many still hate it for obvious reasons.
But no one can deny that JavaScript is damn awesome.
So, let's see some of the amazing things you could do with Vanilla JavaScript.
I'm 200% sure that this list will surprise you!
If you're looking for a friendly community of writers and developers, you can join us at dub.sh/opensouls. You will find a lot of tips to grow as a writer.
Finding operating system details.
Did you know you could find operating system details using simple JS?
The window.navigator
object contains information about the visitor's browser OS details. Some of the OS properties are available under platform property.
You can use the below snippet to get the details.
console.log(navigator.platform);
Preventing the page from refreshing using void(0).
Void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted effects because it will return the undefined primitive value.
It's commonly used in HTML documents that use anchor elements.
For instance, when you click a link, the browser loads a new page or refreshes the same page. It won't happen.
For example, the below link gives the alert without reloading the page.
<a href="JavaScript:void(0);" onclick="alert('Well done!')">
Click Me!
</a>
Redirecting new page.
In vanilla JavaScript, you can redirect the user to a new page by setting the href
property of the location
object, which is a property of the window
object.
The syntax would be as follows:
function redirect() {
window.location.href = "newPage.html";
}
When you call the redirect function, the browser will navigate to newPage.html
.
A little extra explanation.
-
window
: Refers to the browser window. -
location
: A property of the window object that holds information about the current URL. -
href
: A property of the location object that contains the entire URL. Using this, you can change the URL, causing the browser to load the new page.
Validation of emails.
Whenever I want to validate an email, I always look for a perfect snippet.
You also would have seen default functions in libraries to validate email such as in Zod.
The following snippet validates any email with complete logic.
function validateEmail(email) {
var re =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
If you want an easier one that also accepts Unicode characters. You can use the below one!
function validateEmailUnicode(email) {
var re =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(String(email).toLowerCase());
}
This simplified version matches most valid email addresses while avoiding some of the pitfalls of overly complex regular expressions.
Getting the current URL.
Yes, it's possible with only JavaScript!
You can use window.location.href
to both get the current URL and update the URL.
console.log("location.href", window.location.href); // Returns full URL
You can also use document.URL
for read-only purposes (cannot be used to navigate to a new URL) but this solution has issues in Firefox.
console.log("document.URL", document.URL); // Returns full URL (Read-only)
It might not work consistently across all browsers, especially older versions of Firefox (online sources).
So, window.location.href
is generally preferred for both reading and updating the URL.
Detecting a mobile browser using regex.
You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile. WOW!
window.mobilecheck = function () {
var mobileCheck = false;
(function (a) {
if (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
a
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
a.substr(0, 4)
)
)
mobileCheck = true;
})(navigator.userAgent || navigator.vendor || window.opera);
return mobileCheck;
};
I wonder who in the world wrote this snippet :)
Detecting a mobile browser without regex expression.
You can detect mobile browsers by simply running through a list of devices and checking if the userAgent
matches anything. This is an alternative solution for regex expression usage.
function detectmob() {
if (
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/Windows Phone/i)
) {
return true;
} else {
return false;
}
}
This does look much cleaner and easier to understand.
Detecting disabled JavaScript on the page.
You can use the <noscript>
tag to detect whether JavaScript is disabled or not.
The code block inside <noscript>
gets executed when JavaScript is disabled, and is typically used to display alternative content when the page is generated in JavaScript.
<script type="javascript">
// JS related code goes here
</script>
<noscript>
<a href="next_page.html?noJS=true">JavaScript is disabled on the page. Enable it asap!</a>
</noscript>
To get metadata of a module.
You can use the import.meta
object which is a meta-property exposing context-specific metadata to a JavaScript module.
It contains information about the current module, such as the module's URL. In browsers, you might get different metadata than NodeJS.
<script type="module" src="welcome-module.js"></script>;
console.log(import.meta); // { url: "file:///home/user/welcome-module.js" }
Getting the timezone offset from the date.
You can use the getTimezoneOffset
method of the date object. This method returns the time zone difference, in minutes, from the current locale (host system settings) to UTC.
var offset = new Date().getTimezoneOffset();
console.log(offset); // -330
Setting the cursor to wait.
The cursor can be set to wait in JavaScript by using the property called cursor
. Let's perform this using the below function.
function myFunction() {
window.document.body.style.cursor = "wait";
}
You can use it in cases when the page is loading.
To get the status of a checkbox.
You can apply the checked property on the selected checkbox in the DOM. If the value is true it means the checkbox is checked, otherwise it means that it's unchecked.
For instance, the below HTML checkbox element can be checked using javascript as below:
<input type="checkbox" id="checkboxname" value="Agree" /> Agree the
conditions<br />
console.log(document.getElementById(‘checkboxname’).checked); // true or false
Adding CSS to console messages.
Yes, you can even apply CSS styles to console messages similar to HTML text on the web page. Truly awesome :)
console.log(
"%c The text has a purple color, with large font and white background",
"color: purple; font-size: x-large; background: white"
);
Output.
Disable right click on the web page.
The right click on the page can be disabled by returning false from the oncontextmenu
attribute on the body element.
<body oncontextmenu="return false;"></body>
Capture the browser back button.
At first, I didn't even believe that this was possible.
You can do it using the beforeunload
event which is triggered when the window, the document, and its resources are about to be unloaded. This event is helpful to warn users about losing the current data and detecting the back button event.
window.addEventListener('beforeunload', () => {
console.log('Clicked browser back button');
});
Grouping and nesting the console output.
The console.group()
can be used to group related log messages and you can use console.groupEnd()
to close the group.
You can also nest groups which allows you to output messages hierarchically.
For example, if you’re logging a user’s details:
console.group("User Details");
console.log("name: Sudheer Jonna");
console.log("job: Software Developer");
// Nested Group
console.group("Address");
console.log("Street: Commonwealth");
console.log("City: Los Angeles");
console.log("State: California");
// Close nested group
console.groupEnd();
// Close outer group
console.groupEnd();
Output.
You can also use console.groupCollapsed()
instead of console.group()
if you want the groups to be collapsed by default.
WOW! JavaScript, you are really awesome!
Did you find anything good enough here? Do let me know in the comments.
I'm building a Discord community for developers and writers.
Please join us at dub.sh/opensouls.
"Write more, inspire more!"
Top comments (49)
There are some interesting suggestions in here, but a number of them are skirting around logic.
Email regex
This is one that constantly plagues people. In 2006 this was talked about on the Python mailing list, and a StackOverflow question from 2010 is well referenced yet full of changes and "knowledge rot" as things have changed.
While a regex is often "good enough for test purposes" or "good enough for now", relying on them for validating complex rulesets like this can leave you trying to create increasingly complex conditions to resolve unwanted business cases.
Detecting a mobile browser without regex expression.
This seemed a bit off to me. Your example uses seven regular expressions... to avoid regular expressions. 😀
Since these
.match()
expressions are all simple strings, we can actually use.includes()
to solve this without regex:Capture Back Button
Not that
onbeforeunload
will catch Back, forward, and any navigation away from the current page. If you need only the back button, you might try thepopstate
event.Thank you for pointing things out, Samuel 🙌
Yes, frankly there are so many complex rules regarding the edge cases of proper emails that are allowed.
I didn't know about the Capture button, definitely not an expert in this :)
I knew somebody would point out the regex expression as I realized it after publishing. Thank you again for going the extra length to write an alternative solution. I will update the post with this one after a week or so... Let's see if others can find that 😆
Yes, and using native browser functionality works fine for validating email.
This works for email validation without doing the hard work of doing it yourself:
Or, if you want to do it with JS:
Yes, I know that. This post wasn't meant to provide the best methods or practices, such as in validating emails. I just wanted to cover something unique!
15 things you can do with javascript and I still dont like it haha
and thank god I quit doing web dev (and before you criticize, yea I know you can use javascript outside web)
Trust me, I totally understand the feeling, but I love web dev although I use TypeScript 😅
its not randomly that people hate javascript you know right?
Also I compare web development with creating Frankenstein... cause you get pieces of each tech in order to be able to do something that works... for me its a non-sense mess an agglomeration of patching things over and over again creating layers of complexity that should be unnecessary. Sure they tried to fix it with stuff like silverlight, java, php and so on...
but the fact that so many thing are going on with discussion of javascript and web development should mean something at this point so an action should be taken.
Worst part is that it is propagating to other development areas. Instead keeping it simple and straightforward... upgrading the tools that already work, they just patch tech with green tech sometimes unproven tech with exploits or that in order to fix a problem they create 3 more... (also theres no time to consolidate tech, and devs nowadays seem to get bored really quickly)
I guess my point is... you shouldn't need typescript as a separated thing...
Yep, but remove JS and you might end up with almost nothing, as so much stuff is built using JS.
Regarding web development, nobody uses plain JS anymore. Even I prefer Next.js, which is awesome and works without creating layers of complexity. There are better frameworks available now, and I think web development is really awesome at this point :)
Rubbish. Most of my projects use plain JS. How do you think libraries get written?
The web would be a much better place if developers actually learned to code, and use technology appropriate for each use case instead of always resorting to using sledgehammers to crack nuts.
Point out on the doll where the JS hurt you.
Cannot disagree. Where did you move to then.
well I was full stack at the time, that was in 2012.
But I ended up on mobile development at same time.
I actually started using javascript with Appcelerator titanium.
Nowadays I'm an iOS developer
I have to say it can be more satisfying than backend due having visually feedback sometimes... and i find it to be less stressing than web-development cause we are using native languages that support all that you need.
altough our stress are the compilation times. But its getting better and you end up filling your waiting times with some other tasks (you can still lose the track of the logic while waiting)
I see. Thank you for sharing your journey!
I guess having a language that provides you with the toolset really helps save a lot of headache. I may start learning golang for the same reason. I wouldn't be moving to app dev except from maybe learning flutter anytime soon. Because I feel like somewhere down the road we're gonna have an era of progressive webapps gaining more traction.
The second email regex is not good at all - it reports many invalid email addresses as valid:
Yes, I'm aware because I used a basic logic of checking the presence of an
@
symbol, ensures there are characters before and after the@
, and that there is at least one dot.
after the@
.We can definitely upgrade it, but it will get complex, which is why I didn't incorporate all the edge cases!
Yes, better to not use regex at all. Which is pretty straight forward to do.
Yeah, avoid regex for validating emails altogether. You can see my comment where I show how easy it can be done.
navigator.userAgent
is now unreliable & not recommended to use .You can now use
navigator.userAgentData
instead. Though its experimental but still it is read-only, unlikenavigator.userAgent
.Great article! Thanks for gathering all this, I did not know some of those. A couple of comments:
Thanks!
Thanks David 🙌
I didn't know about the second one!
As I mentioned, I just wanted to cover unique stuff...
![Image description](https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi5uyai4fvcjc2c333i3w.png)
To prevent anything from happening when clicking a link, the above example can be shortened by writing the following:
this is identical to
Unfortunately you are right... I cannot imagine any other tool where you have fun to get an unexpected result.
Yeah, the only correlation between unexpected results and fun is JS lol.
👏👏👏
200% bored
It's amazing. I'm glad that I came across this post.
Good stuff, thank you! :)
Super boss 👌🫶
These are OK but not super practical for me. The list format is nice but it is also used for clickbait a lot and starts to get annoying...
Nice job tho :D
Thanks 🙌
Yes, most of them are not practical, and I definitely didn't write it for that use case.
I just wanted to cover unique stuff...
Oh, I see! In that case, you did an awesome job! :D
Keep up the good work bro
Great post, so simple to follow yet so valuable for beginners. Grat job like always man!
Thanks Antonio :)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.