Categories
JavaScript Answers

How to Get the Week of Year of a Given Date in JavaScript?

Sometimes, we want to get the week of the year given a date.

In this article, we’ll look at how to get the week of the year of a given date with JavaScript.

Using Native JavaScript Date Methods

One way to get the week of the year of a given date is to use JavaScript date methods to compute the week of the year of a given date ourselves.

For instance, we can write:

const now = new Date(2021, 3, 1);  
const onejan = new Date(now.getFullYear(), 0, 1);  
const week = Math.ceil((((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7);  
console.log(week)

We have the now date which we want to get the year of the week from.

Then we create the onejan date with which is January 1 of the same year as now .

Then we compute the week of the year by subtracting the timestamps of now and onejan .

And then we divide that by 86400000 to get the number of days difference between the 2 dates.

Then we add the day of the week plus 1 to get the actual number of days difference.

Then we divide that by 7 to get the number of weeks difference.

And we round that number up to the nearest integer with Math.ceil .

Therefore, week is 14.

Use Moment.js

A simpler way to get the week number of the year from a given date is to use moment.js.

To use it, we write:

const now = new Date(2021, 3, 1);  
const week = moment(now).format('W')  
console.log(week)

We pass in the now date to moment to create a moment object.

Then we call format with the 'W' formatting tag to get the week of the year of now .

It rounds down, so week is 13.

Conclusion

We can use JavaScript date methods or use moment.js to get the week of the year.

Categories
JavaScript Answers

How to Return the Index of the Greatest Value in a JavaScript Array?

Sometimes, we want to return the index of the greatest value in a JavaScript array.

In this article, we’ll look at how to return the index of the greater value in a JavaScript array.

Use the Array.prototype.indexOf and Math.max Methods

We can find the index of the greatest value in a JavaScript array with the Math.max and the array’s indexOf method.

For instance, we can write:

const arr = [0, 21, 22, 7];
const index = arr.indexOf(Math.max(...arr));
console.log(index)

We call Math.max with the elements of arr in as arguments by spreading arr into the Math.max method.

This returns the greatest element in arr .

And then we can call arr.indexOf on the greatest element of arr .

And so index is 2, which is the index of value 22 in arr .

Use the Array.prototype.reduce Method

Another way to get the index of the greatest element in an array is to use the JavaScript array’s reduce method.

To use it, we write:

const arr = [0, 21, 22, 7];
const index = arr.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);
console.log(index)

We call reduce on arr with a callback that has the iMax parameter, which is the index of the greatest value of arr so far.

x is the entry of arr being iterated through.

i is the index of x .

arr is the arr array itself.

We return the index of the greatest element by checking if x is bigger than the current element being recorded as the largest so bar, which is arr[iMax] .

If x is bigger than arr[iMax] , we return i .

Otherwise, we return iMax .

0 is the initial value of the index of the greatest element of arr .

And so index is 2 as we saw in the previous example.

Conclusion

We can use the Math.max and Array.prototype.indexOf or Array.prototype.reduce methods to get the index of the greatest elements in a JavaScript array.

Categories
JavaScript Answers

How to Get HTML Elements with Multiple Classes with JavaScript?

Sometimes, we want to get multiple elements with multiple classes with JavaScript.

In this article, we’ll look at how to get HTML elements with multiple classes with JavaScript.

Get HTML Elements with Both Classes

To get HTML elements with both classes, we can use the getElementsByClassName or querySelectorAll methods.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can get the div with text ‘baz’ by writing:

const list1 = document.getElementsByClassName("class1 class2");  
const list2 = document.querySelectorAll(".class1.class2");  
console.log(list1)  
console.log(list2)

We call getElementsByClassName with 'class1 class2' to get the div with both class1 and class2 present.

Likewise, we can do the same with querySelectorAll by using the “.class1.class2” CSS selector.

Then list1 is the HTMLCollection with the 3rd div.

And list2 is the NodeList with the 3rd div.

Get HTML Elements with At Least One Class

We can get HTML elements with at least one class by using the querySelector method.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(".class1,.class2");  
console.log(list)

We use “.class1,.class2” with querySelectorAll to get elements with class1 or class2 or both as the class.

And so list is a NodeList with all 3 elements.

Get HTML Elements with One Class But Not Both

We can also use querySelector to get HTML elements with one class but not both.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we write:

const list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");  
console.log(list)

We use the :not pseudo-selector to exclude class2 with class1 and class1 with class2 .

So list is a NodeList with the first 2 divs.

Get HTML Elements with None of the Classes or One Class Only

To get all the elements with none of the classes or only one of the classes applied to it, we can use the :not pseudo-selector again.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(":not(.class1),:not(.class2)");  
console.log(list)

And we get all the elements in the page but the div with text baz.

Get HTML Elements with None of the Classes

To get the HTML elements with none of the classes, we can use the :not pseudo-selector again.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(":not(.class1):not(.class2)");  
console.log(list)

to select anything but the divs with class1 or class2 .

Conclusion

We can use querySelector to select element with any combinations of the classes applied to an element we want.

Categories
JavaScript Answers

How to Track the User’s Mouse’s Position with JavaScript?

Sometimes, we want to track the user’s mouse’s position with JavaScript.

In this article, we’ll look at how to track the user’s mouse’s position with JavaScript.

Get the Mouse’s Position with the clientX and clientY Properties

We can listen to the mousemove event which is triggered whenever we move the mouse.

Then from the mousemove event object, we can use the clientX and clientY properties to get the x and y coordinate of the mouse cursor on the page.

For instance, we can write:

document.onmousemove = (event) => {  
  const {  
    clientX,  
    clientY  
  } = event  
  console.log(clientX, clientY)  
}

to log the x and y coordinates of the mouse in pixels.

We set an event handler function as the value of the document.onmousemove property.

We attach the event listener to document because we want to listen to the mouse movement on the page.

The method takes the event parameter, which is the mousemove event object.

In the event handler function, we get the clientX and clientY properties to get the x and y coordinates of the mouse cursor’s location on the page.

We can also attach the event listener with the addEventListener method.

For instance, we can write:

document.addEventListener('mousemove', (event) => {  
  const {  
    clientX,  
    clientY  
  } = event  
  console.log(clientX, clientY)  
})

We call addEventListener with 'mousemove’ to listen to the mousemove event.

And then we get the x and y coordinates of the mouse cursor the same way.

Now we should see the x and y coordinates of the mouse cursor logged.

Conclusion

We can use the mousemove event object’s clientX and clientY properties to get the x and y coordinates of the mouse cursor on the page in pixels.

Categories
JavaScript Answers

How to Disable Browser Print Options (Headers, Footers, Margins) from the Page with JavaScript?

Sometimes, we want to disable the headers, footers, and margins when a web page is being printed with JavaScript.

In this article, we’ll look at ways to disable the headers, footers, and margins on the page when it’s being printed with JavaScript.

Disable Headers, Footers, and Margins with CSS with JavaScript

We can disable headers, footers, and margins with CSS with JavaScript.

For instance, we can write:

<!doctype html>
<html>

<head>
    <title>Print Test</title>
    <style type="text/css" media="print">
      @page {
        size: auto;
        margin: 0mm;
      }

      html {
        background-color: #FFFFFF;
        margin: 0px;
      }

      body {
        border: solid 1px blue;
        margin: 10mm 15mm 10mm 15mm;
      }

     </style>
  </head>

  <body>
    <div>Top line</div>
    <div>Line 2</div>
  </body>

</html>

We set some styles for the page when being printed with the @page CSS directive.

We set the size to auto and set margin to 0mm to remove the margins.

Then we set the html styles to a white background color and no margins.

And in the body, we set the border and margin styles.

We set the media attribute to print to make sure the styles are only applied when the page is being printed.

Conclusion

We can disable various parts of the page when they’re printed with printing specific CSS styles.