Java Script
Java Script
2
Introduction
Welcome to this JavaScript HowTo eBook!
Some of the ‘HowTos’ are very simple only requiring a line or two of
code to achieve whereas some are more complex requiring you to write
functions, network requests, and make use of 3rd party APIs.
You can use this eBook however you like - it might be useful to scan
through once quickly to see what is in here and look through some of the
points that you might find useful. Otherwise, it might serve as a handy
reference if you need a bit more help on a particular topic when a
Google search just doesn’t cut it.
I hope you find this guide useful and if you have any feedback,
comments, or spot any errors, reach out on Twitter (@codebubb) and
let me know!
Enjoy!
James.
3
Introduction 3
How to redirect a page with JavaScript 5
How to refresh/reload a page with JavaScript 5
How to get and set cookies with JavaScript 6
How to change button text with JavaScript 8
How to change background color with JavaScript 8
How to hide a button with JavaScript 9
How to disable a button with JavaScript 9
How to get the current URL with JavaScript 10
How to open a new tab with JavaScript 10
How to get a value from a radio button with JavaScript 11
How to print with JavaScript 11
How to add or remove a class with JavaScript 12
How to append HTML with JavaScript 13
How to add style with JavaScript 14
How to close a browser tab with JavaScript 15
How to get a user’s IP address with JavaScript 15
How to get URL parameters with JavaScript 16
How to get an input value with JavaScript 17
How to get a select value with JavaScript 17
How to make a POST request with JavaScript 18
How to get the current date with JavaScript 18
How to set focus with JavaScript 19
How to copy to the clipboard with JavaScript 19
How to validate an email address with JavaScript 20
How to detect key presses with JavaScript 20
How to hover with JavaScript 21
How to move an object with arrow keys with JavaScript 22
How to alert (Yes/No OK/Cancel) with JavaScript 22
How to encrypt data in the browser 23
How to get a timestamp JavaScript 23
How to check if an element is hidden with JavaScript 24
How to create a button with JavaScript 25
How to create a filterable list with JavasScript 26
How to load an image (lazy load) with JavaScript 27
How to get screen / browser size with JavaScript 27
How to format currency with JavaScript 28
How to make the browser full screen with JavaScript 29
How to detect the user’s browser with JavaScript 30
How to split a string in JavaScript 31
How to get form data with JavaScript 31
How to delete cookies with JavaScript 32
How to get a user’s location with JavaScript (Gelocation) 33
4
How to redirect a page with JavaScript
All you need to navigate to a new page with JavaScript is to assign a
new value to the href property, on the location object which is found on
the global Window object of the browser:
window.location.href =
'https://www.juniordevelopercentral.com';
You could wire this up to the click of a button or some other event like
this:
document.querySelector('.someclass')
.addEventListener('click', () => {
window.location.href =
'https://www.juniordevelopercentral.com';
});
You can also bypass the browser’s cache by passing a value of true to
the reload function.
window.location.reload(true);
There is the option to set a timeout to trigger the reload after a certain
time. For example to reload after 5 seconds:
setTimeout(() => {
window.location.reload(true);
}, 5000);
5
How to get and set cookies with JavaScript
You can access the cookies for a particular page by referencing the
cookie property of the document object. i.e.
document.cookie
It might look like you’re going to remove all the other cookies by doing
this but the above will just set a new cookie with the name of ‘name’ and
a value of ‘james’.
If you want to get a particular cookie value you need to manipulate the
cookie string, possibly by splitting it into an array.
document.cookie.split(';')
You will still need to do a bit of work to get the value of a particular
cookie (like splitting each string in the array further by it’s = symbol then
search for the name of the cookie). Alternatively, you can reduce the
split cookie array to a single object.
document.cookie
.split(';')
.map(cookie => cookie.split('='))
.reduce((accumulator, [key, value]) => ({
}), {});
6
How to change button text with JavaScript
To change the text of a button with JavaScript you simply need to target
the particular button element and update it’s textContent (or innerText)
property.
document.querySelector('#myButton')
.textContent = 'New Text';
// or... .innerText = 'Different Text';
document.querySelector('#myElement')
.style.backgroundColor = '#eeffaa';
This might not be ideal for some situations so another approach would
be to use a class and add that to the element when you want to change
it’s background color. For example, set up a class that has a
background-color set to something.
.green {
background-color: green;
}
document.querySelector('#myElement')
.classList.add('green');
7
How to hide a button with JavaScript
There are a few ways to do this.
document.querySelector('#myElement')
.style.visibility = 'hidden';
^^ This hides the element but it still takes up space on the page.
document.querySelector('#myElement')
.style.display = 'none';
^^ This removes the element from the page, it doesn’t take up space any
more (the element is still part of the DOM).
document.querySelector('#myButton')
.setAttribute('disabled', 'disabled');
8
How to get the current URL with JavaScript
There is a property inside the location object which will give you the full
URL of the page you are currently browsing.
window.location.href
In addition, you can pass the string that’s contained in the href property
to construct a new URL object.
new URL(window.location.href)
This will give you access to properties like the hostname, path, origin
etc which makes it easier to extract parts of the URL that you may need.
window.open()
This should open a brand new blank tab for you but the function’s
behaviour is pretty much determined by the browser you’re using. For
example, you might get a new window if your browser has tabs turned
off or something weird like that.
You can also open the tab with a specific page by passing in a URL.
window.open('https://www.juniordevelopercentral.com/')
9
How to get a value from a radio button with
JavaScript
Say you have a radio button or checkbox element and you want to
determine whether it is checked or not, you can determine its state by
accessing the checked property.
If you access the element with a querySelector call, you just need to
check whether the checked property is truthy to determine whether the
input control has been selected or not.
window.print();
You can adjust exactly what gets sent to the print output by determining
CSS rules that format the web content for printing.
10
How to add or remove a class with JavaScript
Each HTML element that you select in JavaScript has a classList
property which contains an object with a few handy functions.
document.querySelector('#myElement')
.classList.add('newCSSClass');
document.querySelector('#myElement')
.classList.remove('newCSSClass');
document.querySelector('#myElement')
.classList.toggle('newCSSClass');
11
How to append HTML with JavaScript
Probably the best approach here is to use one of several functions to
insert new HTML DOM elements into your page. The most flexible is the
insertAdjacentHTML function.
document.querySelector('#myElement')
.insertAdjacentHTML('beforebegin', '<h1>New HTML
Content</h1>');
12
How to add style with JavaScript
So you can add style to elements on the page in a few different ways
with JavaScript.
document.querySelector('#myElement')
.style.color = '#fff';
The other way is to add a new class to the element that has the styles
that you want to add to the element.
You could even do something crazy like create your own style tag and
insert some new CSS rules into it.
13
How to close a browser tab with JavaScript
So you can close a browser tab or window with the close function
available on the window object.
window.close();
// Scripts may close only the windows that were opened by
it.
But depending on your browser you might run into problems such as the
error above. This makes sense as you wouldn’t want tabs randomly
closing without the user’s approval. This should be OK if you’ve just
opened a tab with the window.open() function for example.
fetch('https://api.ipify.org/?format=json')
.then(response => response.json())
.then(data => console.log(data.ip)); // 123.123.123.123
Obviously this is subject to the API’s terms and conditions etc. so for a
production use you’ll want to use a more robust service (rather than a
free one) if you’re relying on the user’s IP address for some purpose.
14
How to get URL parameters with JavaScript
So let’s imagine you’re working with an app that has various different
parameters added to the URL when loading data for example. You
might want to retrieve the various parameters to use in your JavaScript
code.
// https://someurl.com/?search=abcd&user=1234
const p = new URLSearchParams(window.location.search);
p.get('search'); // abcd
You can then call the get function to retrieve any specific parameter you
need.
// https://someurl.com/?search=abcd&user=1234
const p = new URLSearchParams(window.location.search);
const searchParams = Array.from(p.keys())
.reduce((acc, key) => ({ ...acc, [key]: p.get(key) }),
{});
// { search: 'abcd', user: '1234' }
15
How to get an input value with JavaScript
You can get the value of any input with JavaScript (regardless of its
actual type) by directly accessing it’s value property.
/*
<select id="languages">
<option value="javascript">JavaScript></option>
<option value="php">PHP></option>
...
</select>
*/
document.querySelector('#languages').value;
16
How to make a POST request with JavaScript
Probably the simplest way to make a POST request with JavaScript is
using the Fetch API. This should be supported in most modern
browsers. Normally, you would just pass a URL to the fetch function and
it would perform a GET request. To change this to a POST request,
simply pass in an object specifying the method you want to use.
You can use the returned promise from the call to fetch to extract an
object from the data returned and make use of it if the endpoint your
calling returns JSON data.
You might also want to pad the day and month values so they are nicely
formatted.
17
How to set focus with JavaScript
When working with form elements, you can direct the user’s focus to a
particular input field by calling the focus function.
document.querySelector('#myInput').select();
document.execCommand('copy');
If the browser you’re working with supports it, you could also use the
clipboard API found on the navigator object.
window.navigator.clipbaord.writeText('Some text');
The user might also have to provide permission for you to directly write
text to the clipboard.
18
How to validate an email address with
JavaScript
The best way to validate an email is to use a Regular Expression to
check whether your string contains an email.
const complexEmailRegex =
/^(([^<>()\[\]\\.,;:\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,}))$/;
The key property of the event object in the callback will contain the string
representation of the key pressed and there are additional properties on
the event object. For example, you can determine whether the shift key
was pressed by examining the shiftKey property.
19
How to hover with JavaScript
So if you want to change an element’s look you can set up a :hover
selector which modifies its appearance. If however you want to do some
specific task in JavaScript, you can create events to be fired when the
user moves their mouse over and off the element.
With the event listener’s setup, you can call any JavaScript code you
like.
20
How to move an object with arrow keys with
JavaScript
Bit of a strange one but if you have a need to manipulate an HTML
element’s position on the page, you can use JavaScript to alter it’s
position with the arrow keys on your keyboard.
The value returned from the confirm function will be true or false
depending on whether the user presses the OK or cancel button.
21
How to encrypt data in the browser
JavaScript and Web APIs in the majority of browsers don’t have any
common encryption functions built in. You can load in 3rd party scripts
for common hashing algorithms.
Like md5:
// <script
src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.
12.0/js/md5.min.js"></script>
Or sha256:
// <script
src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.
0/sha256.min.js"></script>
Date.now(); // Milliseconds
Math.round(Date.now() / 1000); // Seconds
22
How to check if an element is hidden with
JavaScript
If you want to check if an element is actually hidden then you can’t
actually just access it’s style property with JavaScript (as the properties
on the object will be empty unless you have already assigned a value
with JavaScript).
You pass in a reference to the element you are checking and it’s
probably worth checking the value of both the display and visibility
properties.
You could combine this into a function to check both at the same time.
23
How to create a button with JavaScript
The same way you would create any new elements really - either by
assigning a new blob of HTML as a string or creating the individual
elements from scratch.
24
How to create a filterable list with JavaScript
If you have a list of items you might want to filter them based on some
user input. You can do this dynamically by using a regular expression
for matching.
/*
<ul id="list">
<li>Eggs</li>
<li>Bacon</li>
<li>Sausages</li>
...
</ul>
<input id="filter" type="text">
*/
You will need to also add a class of hidden in order to make the items
disappear from the list or alternatively you could update the inline styles
of the elements on the fly.
25
How to load an image (lazy load) with
JavaScript
So there are lots of libraries available for handling lazy loading of images
but if you just want to show a temporary image (like a loader for
example) whilst a particularly large image is being downloaded, you can
simply create a second img element and load the big image to it. Once
it’s finished, you can swap out the temporary loading image.
26
How to get screen / browser size with
JavaScript
You can access either the inner dimensions of the browser window or
the outer dimensions. The inner dimension will change if for example
you have your dev tools open.
window.outerWidth;
window.outerHeight;
window.innerWidth;
window.innerHeight;
// Also...
window.screen;
There is also the screen object available on the window object which
has loads of useful information like the available screen size, orientation
etc. although it’s probably best not to use this for mobile detection.
This way you can keep your values with a type of number but use the
formatter when you want to display them in a more human readable
format.
27
How to make the browser full screen with
JavaScript
With JavaScript you can select a particular element on the page and
then switch the browser to full screen mode, only showing that element.
document.querySelector('#container')
.requestFullScreen();
If you try this out, the downside is that you’ll get the element on the page
but the rest of the page will be black / white (depending on which
browser you’re using).
document.documentElement
.requestFullScreen();
28
How to detect the user’s browser with
JavaScript
It’s a bad idea really but if you have a need to you can use feature
detection or user agent sniffing.
The user agent method involves looking at the string provided on the
navigator object and seeing if you can recognise the browser.
window.navigator.userAgent;
// "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/80.0.3987.122 Safari/537.36"
You could therefore look for the string of ‘Chrome’ to determine whether
the user is using the Chrome browser but what if you were checking for
‘Safari’? This would give a false positive in this case.
If you are doing browser detection to customise the code that runs, try
checking whether the feature you are trying to use exists on the browser
to determine if you need to use a fallback.
try {
fetch;
} catch (error) {
isFetchSupported = false;
}
29
How to split a string in JavaScript
Use the split function of course! But there are a few extra things you can
do with it.
const string = 'The quick brown fox, jumped over the lazy
dog';
string.split('');
// Split every character
string.split(',');
// Split based on the delimiter provided
string.split(' ');
// Get every word (assuming only one whitespace per word)
string.split(/\s+/);
// Or match using a pattern, like matching more than one
whitespace
string.split(' ', 3);
// Finally, limit the number of returned items
/*
<form id="myForm">
<input id="myInput" type="text">
<button>Submit</button>
*/
The only problem with the ‘elements’ approach is that it will return any
unnecessary form elements, like buttons, aswell.
30
How to delete cookies with JavaScript
To remove a cookie from the browser, you simply need to assign it an
expiration date in the past.
You still need the assignment operator when referencing the cookie but
the value you give it can be blank as above.
31
How to get a user’s location with JavaScript
(Gelocation)
If your browser supports it you can request the user’s location from the
Geolocation API.
window.navigator
.geolocation.getCurrentPosition(console.log,console.log);
These aren’t much use on their own if you’re looking to identify the
user’s location in a human readable format so you’ll need to use a
lookup service like opencagedata.com (account and API key required) to
translate the longitude and latitude values.
fetch(`https://api.opencagedata.com/geocode/v1/json?q=${la
titude}+${longitude}&key=1234`)
.then(response = response.json();
.then(console.log);
Window.navigator
.geolocation.getCurrentPosition(successfulLookup,
console.log);
32