15 amazing things you can do with simple JavaScript 🤯
Anmol Baranwal
Posted on July 1, 2024
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!"
Posted on July 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.