Categories
JavaScript Answers

How to Jump to an Anchor Element by Using JavaScript?

We can use the location.href property to get the URL without the hash.

Then we can append the hash to it.

And then we can remove the hash from the URL in the URL bar with history.replaceState .

For instance, we can write the following HTML:

<button>
  jump
</button>
<div id='a'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi rhoncus dignissim lacus, ac ullamcorper ex aliquam vel. Donec nec luctus augue, sit amet porttitor diam. Ut sit amet mi ac risus congue ultricies. Donec et condimentum nisi, sit amet consequat felis. Nam velit nibh, blandit non nunc eget, ullamcorper suscipit ex.
</div>
<div id='b'>
  Phasellus faucibus fringilla ullamcorper. Vivamus gravida urna vel odio rutrum rutrum. Vivamus pretium, orci eget cursus tempus, quam elit rutrum est, vel fermentum sapien odio sit amet velit. Etiam cursus pulvinar massa, non maximus dolor vestibulum id. Morbi mi mauris, iaculis ac sem a, porta vehicula risus. Curabitur tincidunt sollicitudin sapien, ac tristique ligula ullamcorper eget. Donec tincidunt orci non ligula auctor ullamcorper. Aliquam mattis elit mauris, at posuere nulla lobortis id.
</div>

Then we can add a button to scroll down to the div with ID b by writing:

const jump = (h) => {
  const url = location.href;
  location.href = "#" + h;
  history.replaceState(null, null, url);
}
`
const button = document.querySelector('button')
button.addEventListener('click', () => {
  jump('b')
})

We have the jump function with the h parameter which is the ID of the element we want to scroll to.

Next, we get the current URL with location.href .

Then we add the hash with the ID h to it to jump to the element with ID h .

And then we call history.replaceState with url as the 3rd argument to replace the hash URL with the original.

Next, we get the button with document.querySelector .

And then we call addEventListener with 'click' to add a click listener.

The 2nd argument is the click listener which calls jump with 'b' to scroll to the div with ID b .

Categories
JavaScript Answers

How to Check if a Value is Within a Range of Numbers in JavaScript?

We can use the JavaScript’s greater than or equal to and less than or equal to operators to check if a number is in between 2 numbers.

For instance, we can write:

const between = (x, min, max) => {
  return x >= min && x <= max;
}
// ...
const x = 0.002
if (between(x, 0.001, 0.009)) {
  // something
}

We create the between function with the x , min and max parameters.

x is the number we want to check if it’s between min and max .

Then we call it in the if statement to see if x is between 0.001 and 0.009.

Use the Lodash inRange Method

We can also use the Lodash inRange method to check if a number is in between 2 numbers.

To use it, we write:

const x = 0.002
if (_.inRange(x, 0.001, 0.009)) {
  // something
}

We call inRange with the number x that we want to check if it’s between 0.001 and 0.009.

Categories
JavaScript Answers

How to Create an Array of Functions with JavaScript?

We can put functions in an array as we do with any other values.

For instance, we can write:

const firstFunction = () => {
  //...
}

const secondFunction = () => {
  //...
}

const thirdFunction = () => {
  //...
}

const forthFunction = () => {
  //...
}

const arr = [
  firstFunction,
  secondFunction,
  thirdFunction,
  forthFunction
]

arr[0]()
arr[1]()
arr[2]()
arr[3]()

We have 4 functions, firstFunction , secondFunction , thirdFunction , and forthFunction .

And then we put them all in the arr array, separating them with commas.

Finally, we can call them by getting the function by their index from arr and call them as we do with any other function.

Categories
JavaScript Answers

How to Capitalize the First Letter of Each Word in a String Using JavaScript?

We can use the string toUpperCase and substring methods to convert each word in a string to have their first letter in uppercase.

For instance, we can write:

const titleCase = (str) => {
  const splitStr = str.toLowerCase().split(' ');
  for (const [i, str] of splitStr.entries()) {
    splitStr[i] = str[0].toUpperCase() + str.substring(1);
  }
  return splitStr.join(' ');
}

console.log(titleCase("I'm a little tea pot"));

We create the titleCase function with the str string parameter.

We split the string by the space character with the split method.

Then we loop through each string in the split string array with the for-of loop.

We get the index i and string str from each entry by destructuring the entries returned by entries .

After that, we get the first character of str and convert that to uppercase. Then we concatenate that with the rest of the str string that we get from substring .

Finally, we join the string back together with a space character in between each word with join .

Therefore, the console log should log 'I’m A Little Tea Pot’ .

Categories
JavaScript Answers

How to Get the Element at the Specified Position with JavaScript?

We can use the document.elementFromPoint method to get the element at the given x-y coordinates.

Each coordinates is in pixels.

For instance, if we have the following div element:

<div>  
  hello world  
</div>

Then we can use the document.elementFromPoint method to get the div by writing:

const el = document.elementFromPoint(10, 10);  
console.log(el)

The coordinates are relative to the top left corner.

The first argument is the x coordinate and the 2nd argument is the y coordinate.

So the first argument is 10 pixels to the right of the top left corner.

And the 2nd argument is 10 pixels below the top left corner.