Categories
JavaScript Answers

How to Scroll to the Top of the Page with JavaScript?

Sometimes, we need to scroll to the top of a web page programmatically.

In this article, we’ll look at how to scroll to the top of the page with JavaScript.

Scroll to the Top of the Page with JavaScript

We can scroll to the top of the page with JavaScript with the window.scrollTo method.

For instance, if we have the following HTML code:

<div>

</div>
<button>
  scroll to top
</button>

Then we can create a page of content with JavaScript and make the button scroll to the top of the page by writing:

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

button.addEventListener('click', () => {
  window.scrollTo(0, 0);
})

We get the div with querySelector .

Then we have a for loop which creates a p element with document.createElement .

And we set textContent to it.

And then we call appendChild to append the p element to the div.

To make the button scroll the page to the top when we click it, we call addEventListener on the button.

In the callback, we call window.scrollTo with the x and y coordinates to scroll to respectively.

Smooth Scrolling Animation

We can add smooth scrolling animation when we’re scrolling.

To do this, we pass in an object to scrollTo instead.

For instance, we can write:

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

button.addEventListener('click', () => {
  window.scrollTo({
    top: 0,
    left: 0,
    behavior: 'smooth'
  });
})

We pass in an object with the top and left properties to set the x and y coordinates to scroll to respectively.

Also, we set the behavior property to 'smooth' to make the scrolling animation smooth.

This is better making the page jump straight to the top without the behavior options as we have in the first example.

Conclusion

We can use the window.scrollTo method to make a page scroll to the top with JavaScript.

We can set the location to scroll to and whether animation is shown or not during scrolling.

Categories
JavaScript Answers

How to Find an Object by ID in an Array of JavaScript Objects?

Finding an object by ID or another property in an array of JavaScript objects is something that we’ve to do a lot in our JavaScript code.

In this article, we’ll look at how to find an object by ID in an array of JavaScript objects in our code.

Array.prototype.find

JavaScript arrays come with the find method to let us find an object in an array with the condition we specify in the callback and return the first instance of the object that meets the condition.

If the object with the given condition isn’t found, then it returns undefined .

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const obj = arr.find(x => x.id === 2)
console.log(obj)

arr is an array of objects with the id and foo properties.

Then we call the find method with a callback that returns the condition with the object we’re looking for.

The x parameter is the object that’s being iterated through to find the object.

Therefore, obj is:

{id: 2, foo: "bar"}

Array.prototype.findIndex

The findIndex method lets us find the item that matches the given condition, but it returns the index of the first instance of the element that meets the condition instead of returning the whole object.

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const index = arr.findIndex(x => x.id === 2)
console.log(index)

Then index is 1 since the callback specifies that we find the first object with the id property set to 2.

{id: 2, foo: "bar"}

Array.prototype.filter

The filter method also lets us find array entries that meet the given condition.

It returns an array with all the elements that meet th given condition.

For instance, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const results = arr.filter(x => x.id === 2)

The callback is the same as the other examples as it returns the condition of the items we want to find.

Then we get:

[
  {
    "id": 2,
    "foo": "bar"
  }
]

If we only want to get one element from the array, we can get it by index by writing:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const results = arr.filter(x => x.id === 2)
console.log(results[0])

Then we get:

{
  "id": 2,
  "foo": "bar"
}

Also, we can write:

const arr = [{
  id: 1,
  foo: 'bar'
}, {
  id: 2,
  foo: 'bar'
}]
const [result] = arr.filter(x => x.id === 2)

to destructure the first result from the returned array.

Conclusion

We can use native JavaScript array methods to find an object by ID in our code.

Categories
JavaScript Answers

How to Check if a JavaScript String Starts With Another String?

Sometimes we have to check whether a JavaScript string starts with a given substring.

In this article, we’ll look at how to check if a JavaScript string starts with another string.

String.prototype.startsWith

ES6 added the startsWith method to a string.

For instance, we can write:

console.log("hello world".startsWith("hello"));

We call startsWith on the string and we pass in the substring that we want to check whether the 'hello world' string starts with it.

The console log should show true since 'hello world' starts with 'hello' .

String.prototype.substring

Another way to check if a string starts with the given substring is to use the substring method.

It takes the start and end index as the argument.

And it returns the substring beginning with the starting index to the end index minus 1.

Therefore, we can write:

const data = 'hello world'  
const input = 'hello'  
console.log(data.substring(0, input.length) === input)

data is the full string.

substring has arguments 0 and input.length to extract the substring from index 0 to input.length  —  1 .

So subtring should return 'hello' , which is the same as input .

Regex Test

We can search for a given pattern with JavaScript regex object’s test method.

And we can check whether a string begins with a given substring by using the ^ symbol to start searching for a pattern at the beginning of a string.

For instance, we can write:

console.log(/^hello/.test('hello world'))

to check whether 'hello world' starts with hello .

Equivalently, we can use the RegExp constructor to create the regex object:

console.log(new RegExp('^hello').test('hello world'))

This lets us pass in a regex string to create the regex object instead of creating a regex literal.

So it’s handy for creating regex objects dynamically.

String.prototype.lastIndexOf

A JavaScript string also comes with the lastIndexOf method to check the last index of a given substring in a string.

To use it to check whether a string starts with a given substring, we can write:

console.log('hello world'.lastIndexOf('hello', 0) === 0)

We call lastIndexOf with the substring we’re searching for like the first argument.

The 2nd argument is the index that we start searching for the substring from.

If it returns 0, then we know the substring is located in index 0 and starts there.

String.prototype.indexOf

We can replace lastIndexOf with indexOf to get the same behavior.

Instead of searching for the last instance of a substring with lastIndexOf .

We can search for the search instance of a substring with indexOf .

It makes no difference to us since we just want to know if a string starts with a given substring.

For instance, we can write:

console.log('hello world'.indexOf('hello', 0) === 0)

to do the check.

Conclusion

There are many JavaScript string methods we can use to check whether a string starts with the given substring.

Categories
JavaScript Answers

How to Display a JavaScript Object in the Browser Console?

To make debugging easier, we can display an object we want to inspect in the console.

There are various ways to do this.

In this article, we’ll look at how to display a JavaScript object in the browser console.

console.log

The console.log method will log an object’s content directly to the console.

For instance, we can write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
console.log(obj)

We just pass in obj into console.log to log its content directly to the browser’s console.

JSON.stringify

The JSON.stringify lets us convert a JavaScript object into a JSON string.

For instance, we can write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
const str = JSON.stringify(obj);  
console.log(str)

Then we see:

{"a":1,"b":2,"child":{"c":3}}

in the console.

To make reading it easier, we can add indentation to the properties that are stringified.

To do this, we write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
const str = JSON.stringify(obj, undefined, 2);  
console.log(str)

The 3rd argument of JSON.stringify specifies the indentation of each stringified.

2 means 2 spaces.

So we should get:

{  
  "a": 1,  
  "b": 2,  
  "child": {  
    "c": 3  
  }  
}

logged into the console.

The console.dir Method

The console.dir method also logs an object into the console like console.log .

For instance, we can write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
console.dir(obj)

to log obj into the console.

The console.table Method

The console.table method lets us log an object’s properties in a tabular format.

For instance, if we write:

const obj = {  
  a: 1,  
  b: 2,  
  child: {  
    c: 3  
  }  
}  
console.table(obj)

Then we get a table with the properties and values of an object in a table.

Conclusion

Browsers come with many methods to log objects into the console.

Categories
JavaScript Answers

How to Retrieve the Position of an HTML Element Relative to the Browser Window?

Retrieving the position of an HTML element relative to the browser window is something that we’ve to sometimes in our JavaScript web app.

In this article, we’ll look at ways to get the position of an HTML element relative to the browser window.

The getBoundingClientRect Method

The getBoundingClientRect method is available with HTML element node objects to let us get the position of an element.

For instance, if we have the following HTML:

<div>  
  hello world  
</div>

Then we can call getBoundingClientRect by writing:

const div = document.querySelector('div')  
const rect = div.getBoundingClientRect();  
console.log(rect.top, rect.right, rect.bottom, rect.left);

We get the div element with querySelecttor .

Then we call getBoundingClientRect to get the position.

leftand top has the x and y coordinates of the top left corner of the element.

right and bottom has the x and y coordinates of the bottom right corner of the element.

Element’s Position Relative to the Whole Page

We’ve to add scrollX and scrollY to get the element’s position relative to the whole page.

For instance, we can write:

const div = document.querySelector('div')  
const getOffset = (el) => {  
  const rect = el.getBoundingClientRect();  
  return {  
    left: rect.left + window.scrollX,  
    top: rect.top + window.scrollY  
  };  
}

console.log(getOffset(div));

scrollX returns the number of pixels that the document is currently scrolled horizontally.

And scrollY returns the number of pixels that the document is currently scrolled vertically.

offsetLeft and offsetTop

offsetLeft and offsetTop lets us get the position of the upper left corner of the element relative to the nearest parent.

For block-level elements, offsetTop, offsetLeft describe the border-box of an element relative to the offsetParent.

For inline elements, offsetTop, offsetLeft describe the positions of the first border-box.

For instance, we can use it by writing:

const div = document.querySelector('div')  
console.log(div.offsetLeft, div.offsetTop);

Conclusion

We can get the position of an element with various properties in JavaScript.