DEV Community

Cover image for 15 amazing things you can do with simple JavaScript 🤯
Anmol Baranwal
Anmol Baranwal Subscriber

Posted on • Updated on

15 amazing things you can do with simple JavaScript 🤯

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);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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";
}
Enter fullscreen mode Exit fullscreen mode

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());
}
Enter fullscreen mode Exit fullscreen mode

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());
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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" }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

output

Output

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";
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
);
Enter fullscreen mode Exit fullscreen mode

Output.

console message

Note: All CSS styles can be applied to console messages.

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>
Enter fullscreen mode Exit fullscreen mode

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');
 });
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Output.

console group 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.

If you like this kind of stuff,
please follow me for more :)
profile of Twitter with username Anmol_Codes profile of GitHub with username Anmol-Baranwal profile of LinkedIn with username Anmol-Baranwal

"Write more, inspire more!"

Ending GIF waving goodbye

Top comments (53)

Collapse
 
oculus42 profile image
Samuel Rouse

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:

function detectMobile() {
    const userAgent = navigator.userAgent.toLowerCase();
    const agents = [
        'android',
        'webos',
        'iphone',
        'ipad',
        'ipod',
        'blackberry',
        'windows phone',
    ];
    return agents.some(agent => userAgent.includes(agent));
}
Enter fullscreen mode Exit fullscreen mode

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 the popstate event.

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thank you for pointing things out, Samuel 🙌

  1. Yes, frankly there are so many complex rules regarding the edge cases of proper emails that are allowed.

  2. I didn't know about the Capture button, definitely not an expert in this :)

  3. 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 😆

Collapse
 
chandra_pantachhetri profile image
Chandra Panta Chhetri

Thank you, the detect mobile browser logic looks much cleaner and readable :)

Collapse
 
jon49 profile image
Jon Nyman • Edited

Yes, and using native browser functionality works fine for validating email.

Collapse
 
77pintu profile image
77pintu

Thanks for the great post

Collapse
 
invincibl3 profile image
Victorious Adelakun

Actually, this is a lot to take in as i am still learning 😂.
Thanks for this.

Collapse
 
jon49 profile image
Jon Nyman • Edited

This works for email validation without doing the hard work of doing it yourself:

<input type=email>
Enter fullscreen mode Exit fullscreen mode

Or, if you want to do it with JS:

let emailInput = document.createElement('input')
emailInput.type = 'email'
function isValidEmail(value) {
  emailInput.value = value
  return !!emailInput.value
     && emailInput.validity.valid
}


// Is valid email?
// empty false
console.log('empty', isValidEmail(''))
// george false
console.log('george', isValidEmail('george'))
// george@example.com true
console.log('george@example.com', isValidEmail('george@example.com'))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anmolbaranwal profile image
Anmol Baranwal

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!

Collapse
 
jonathands profile image
Jonathan DS

Email inputs accepts stuff like jurge@localhost Or mail@company Without the TLD because they are technically valid emails.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

The second email regex is not good at all - it reports many invalid email addresses as valid:

/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test('me@.....a.......')  // true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anmolbaranwal profile image
Anmol Baranwal

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!

Collapse
 
jon49 profile image
Jon Nyman

Yes, better to not use regex at all. Which is pretty straight forward to do.

Collapse
 
jon49 profile image
Jon Nyman

Yeah, avoid regex for validating emails altogether. You can see my comment where I show how easy it can be done.

Collapse
 
navyseai profile image
João Serra

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)

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Trust me, I totally understand the feeling, but I love web dev although I use TypeScript 😅

Devs hate JS a bit too much :)

Collapse
 
navyseai profile image
João Serra • Edited

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...

Thread Thread
 
anmolbaranwal profile image
Anmol Baranwal

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 :)

Thread Thread
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Regarding web development, nobody uses plain JS anymore.

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.

Collapse
 
harmeetjaipur profile image
lazinessincarnate

Point out on the doll where the JS hurt you.

Collapse
 
okayhead profile image
Shashwat jaiswal

Cannot disagree. Where did you move to then.

Collapse
 
navyseai profile image
João Serra • Edited

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)

Thread Thread
 
okayhead profile image
Shashwat jaiswal

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.

Collapse
 
vcvishakha profile image
Vishakha Tak

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, unlike navigator.userAgent.

Collapse
 
dparramon profile image
David Parramon • Edited

Great article! Thanks for gathering all this, I did not know some of those. A couple of comments:

  • Disabling right click for a website can pose accessibility issues, I would highly recommend not do it. Also, I believe is browser dependent.
  • Detect user agent is going to be spotty at best, there is a lot of user agents on the market and each browser treats it in a different way and nothing prevents them from changing the name they use, or will be future proof at all.

Thanks!

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Thanks David 🙌
I didn't know about the second one!

As I mentioned, I just wanted to cover unique stuff...
Image description

Collapse
 
sabotagedninja profile image
Bastiaan de Jong

To prevent anything from happening when clicking a link, the above example can be shortened by writing the following:

href="javascript:;"
Enter fullscreen mode Exit fullscreen mode

this is identical to

href="javascript:void(0);"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
efpage profile image
Eckehard • Edited

I love JavaScript because it's full of surprises...

Unfortunately you are right... I cannot imagine any other tool where you have fun to get an unexpected result.

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

Yeah, the only correlation between unexpected results and fun is JS lol.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.