Categories
JavaScript Answers

How to Create and Read a Value from a Cookie with JavaScript?

Sometimes, we may want to create and read a value from a cookie with JavaScript.

In this article, we’ll look at how to create and read a value from a cookie with JavaScript.

Creating a Cookie

We can create a cookie by setting the document.cookie property with a string that has the key-value pair with the expires key-value pair attached after it.

For instance, we can write:

const setCookie = (name, value, days = 7, path = "/") => {
  const expires = new Date(Date.now() + days * 864e5).toUTCString();
  document.cookie =
    name +
    "=" +
    encodeURIComponent(value) +
    "; expires=" +
    expires +
    "; path=" +
    path;
};

We create the setCookie function that takes the name , value , days , and path parameters.

name is the key of the cookie.

value is the corresponding value of the key of the cookie.

days is the number of days until it expires.

path is the path for the cookie.

expires has the date string of the expiry date.

toUTCString returns the date string in UTC.

Then we set document.cookie with the name and value with = between it.

And we concatenate that with the expires key-value pair after the semicolon.

And we add the path after that.

Getting a Cookie

There’s no easy way to get a JavaScript cookie with native methods.

We’ve to extract the cookie ourselves given the key.

To do this, we write:

const getCookie = (name) => {
  return document.cookie.split("; ").reduce((r, v) => {
    const parts = v.split("=");
    return parts[0] === name ? decodeURIComponent(parts[1]) : r;
  }, "");
};

We split the document.cookie string with ; .

Then we call reduce on the string array to split the parts by the = sign with split .

Then we check if the first entry of the array is the same as name .

If it is, then we call decodeURIComponent with parts[1] to decode the value.

Otherwise, we return r which has the remaining parts of the split document.cookie string.

The 2nd argument of reduce is an empty string which is the initial return value of reduce .

Now when we call the 2 functions as follows:

setCookie("foo", "bar", 10);
console.log(getCookie("foo"));

We see that the console log should return 'bar' .

Conclusion

We can get and set the document.cookies string property to get and set cookies with JavaScript.

Categories
JavaScript Answers

How to Prepend Values to a JavaScript Array?

Sometimes, we may want to prepend values to a JavaScript array.

In this article, we’ll look at how to prepend values to a JavaScript array.

Array.prototype.unshift

We can use the unshift method to prepend one or more items to an array.

For instance, we can write:

const a = [1, 2, 3, 4];
a.unshift(0);
console.log(a)

unshift prepends an item in place, so we get:

[0, 1, 2, 3, 4]

as the new value of a .

We can pass in as many values as we want, so we can write:

const a = [1, 2, 3, 4];
a.unshift(-1, 0);
console.log(a)

Then we get:

[-1, 0, 1, 2, 3, 4]

as the value of a .

We can also spread an array’s value as arguments of unshift .

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
a.unshift(...b);
console.log(a)

Then we get the same result as the previous example since we spread the entries of b as arguments of unshift .

Using the Spread Operator

We can also use the spread operator to prepend values to an array.

This will return a new array instead of pretending items in place to an existing array.

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
const c = [...b, ...a]
console.log(c)

We create the c variable and assign it an array with the values of b spread into the new array first.

Then we spread the entries of a into the same array next.

So c is:

[-1, 0, 1, 2, 3, 4]

as a result.

Array.prototype.concat

Another array method we can use to prepend items to an array is to use the concat method.

It also returns a new array instead of prepending items in-place.

For instance, we can write:

const a = [1, 2, 3, 4];
const b = [-1, 0]
const c = b.concat(a)
console.log(c)

to call concat on b with the array a .

This lets us add the entries from a after the entries of b in the returned array.

So c is [-1, 0, 1, 2, 3, 4] as a result.

Conclusion

We can use various array methods or the spread operator to prepend entries into an array.

Categories
JavaScript Answers

How to Check the Size of a Selected File with JavaScript?

Sometimes, we may want to check the size of a selected file with JavaScript.

In this article, we’ll look at how to check the size of a selected file with JavaScript.

Using the FileReader API

Almost all modern browsers should support the FileReader API.

For instance, we can use it by writing the following HTML:

<form action='#'>
  <input type='file' id='fileinput'>
  <input type='button' id='btnLoad' value='Load'>
</form>

Then we can write the following JavaScript code:

const addPara = (text) => {
  const p = document.createElement("p");
  p.textContent = text;
  document.body.appendChild(p);
}

document
  .getElementById("btnLoad")
  .addEventListener("click", () => {
    const input = document.getElementById('fileinput');
    if (!input.files[0]) {
      addPara("Please select a file before clicking 'Load'");
    } else {
      const file = input.files[0];
      addPara(`File ${file.name} is ${file.size} bytes in size`);
    }
  });

In the HTML code, we have a form with a input with type file .

And we have a button that lets us show the file info when we click it.

In the JavaScript code, we have the addPara function that creates a p element and set the text as its content.

Then we call getElementById to get the button input element.

Then we call addEventListener to add a click listener.

In the click listener, we get the file input with getElementById .

Then we check if input.files[0] exists.

input.files[0] has the first file selected.

If there’s no file, we call addPara to show a message.

Otherwise, we call addPara to show the file info.

file.name has the filename of the selected file.

file.size has the size of the selected file in bytes.

When we select a file and click Load, we should see the file info of the selected file.

Conclusion

We can check the info of the selected file easily with the FileReader API.

Categories
JavaScript Answers

How to Get a Subarray from a JavaScript Array?

Sometimes, we may want to get a subarray from a JavaScript array.

In this article, we’ll look at how to get a subarray from a JavaScript array.

Array.prototype.slice

The JavaScript array’s slice instance method takes the beginning and ending index of the array that we want to extract.

The end index is excluded.

It returns an array with the items starting from the beginning index and the end index minus 1.

For instance, we can write:

const arr = [1, 2, 3, 4, 5];
const sub = arr.slice(1, 3)
console.log(sub)

Then sub is [2, 3] since we extract the array from index 1 to 2 and return it.

We can also pass in negative indexes to the slice method.

Negative indexes mean we start counting from the end of the array instead of the start.

So -1 is the last element of the array, -2 is the 2nd last one, and so on.

So we can replace the code above with:

const arr = [1, 2, 3, 4, 5];
const sub = arr.slice(1, -2)
console.log(sub)

and get the same value for sub .

Conclusion

We can use the JavaScript array’s slice method to extract a subarray from a JavaScript array.

Categories
JavaScript Answers

How to Check if a Scrollbar is Visible with JavaScript?

Sometimes, we may want to check if a scrollbar is visible in our JavaScript web app.

In this article, we’ll look at how to check if a scrollbar is visible with JavaScript.

Comparing scrollHeight with clientHeight

The HTML element’s scrollHeight property is a read-only property that is a measurement of the height of an element’s content.

It includes the content that’s not visible on the screen due to overflow.

It’s measured in pixels.

The HTML element’s clientHeight property is a read-only property that is zero for elements that have no CSS or inline frame layouts.

And it’s the number of pixels of the inner height including the padding but excluding the borders, margins, and horizontal scrollbars otherwise.

Therefore, we can compare the scrollHeight of an element with its clientHeight to determine whether a scrollbar would be shown.

If scrollHeight is bigger than clientHeight , then we know the scrollbar would be shown since there would be overflow text.

For instance, we can write the following HTML:

<p>
  hello world
</p>

<div style='height: 100px; overflow-y: auto'>

</div>

Then we can write the following JavaScript:

const scrollbarVisible = (element) => {
  return element.scrollHeight > element.clientHeight;
}

const p = document.querySelector('p')
const div = document.querySelector('div')

for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

console.log(scrollbarVisible(p))
console.log(scrollbarVisible(div))

We create the scrollbarVisible function to return the result of comparing the element ‘s scrollHeight with its clientHeight .

Then we get the p and div elements with document.querySelector .

Next, we have a for loop to create p elements and append them as child elements of the div.

Since we set the height of the div to 100px and overflow-y is set to auto , we can scroll through the content we added.

Then finally, we log the returned result of the scrollbarVisible function on the p and div elements.

Then first console log should log false since there’s no overflowing content.

And the 2nd console log should log true since there is overflowing content.

Conclusion

To check if a scrollbar is present for an element, we can compare the scrollHeight value with its clientHeight value, both are in pixels.