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.

Categories
JavaScript Answers

How to Remove Insignificant Trailing Zeros from a JavaScript Number?

Sometimes, we want to remove insignificant trailing zeroes from a JavaScript number.

In this article, we’ll look at ways to remove insignificant trailing zeroes from a JavaScript number.

Using the Number.prototype.toString Method

We can convert a number to a number string with the JavaScript number’s toString method.

The toString method will remove any insignificant trailing zeroes from the number.

For instance, if we have:

const n = 1.245000  
const noZeroes = n.toString()  
console.log(noZeroes)

Then noZeroes is '1.245' .

Using the Number.prototype.toFixed Method

We can use the JavaScript number to toFixed method to convert a number into the number string with the number of decimal places we want to show.

Then we can convert it back to a number with the parseFloat or Number functions.

For instance, we can write:

const n = 1.245000  
const noZeroes = parseFloat(n.toFixed(5));  
console.log(noZeroes)

We call toFixed with 5 to return a number with 5 decimal places.

The toFixed method automatically discards the insignificant trailing zeroes.

After that, we use parseFloat to convert the number string back to a number.

Therefore, we get the same result as the previous example.

We can replace parseFloat with Number by writing:

const n = 1.245000  
const noZeroes = Number(n.toFixed(4));  
console.log(noZeroes)

and get the same result.

Conclusion

To remove insignificant trailing zeroes from a number, we can call toFixed or toString to convert it to a number string.

And to convert the number string back to a number, we can use the parseFloat or Number functions.

Categories
JavaScript Answers

How to Match an Exact String with JavaScript?

Sometimes, we want to find an exact string within our JavaScript code.

In this article, we’ll look at how to find an exact string with JavaScript.

Using the String.prototype.match Method

We can use the JavaScript string instance’s match method to search for a string that matches the given pattern.

For instance, we can write:

const str1 = 'abc'
const str2 = 'abcd'
console.log(str1.match(/^abc$/))
console.log(str2.match(/^abc$/))

to call match with a regex that matches the exact word.

^ is the delimiter for the start of the word.

And $ is the delimiter for the end of the word.

Therefore, the regex matches the exact word in between the delimiters.

The first console log should log 'abc' as a match.

And the 2nd console log should log null .

We can convert the matched strings to an array.

For instance, we can write:

const str1 = 'abc'
console.log([...str1.match(/^abc$/)])

We use the spread operator to convert the match object to an array since the match object is an iterable object.

Conclusion

We can match an exact string with JavaScript by using the JavaScript string’s match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

Categories
JavaScript Answers

How to Avoid Browser Popup Blockers with JavaScript Code?

Sometimes when we try to open a window with the window.open method, we may see the browser permission popup asking for permission to open the popup created by window.open .

In this article, we’ll look at how to avoid browser popup blockers within our JavaScript code.

Avoid Calling window.open in Async Functions

To avoid the permission popup for opening the popup, we should use avoid calling window.open in a function that returns a promise or in callbacks for functions like setTimeout , setInterval , or any other async function.

This is because, a popup can only be opened from an app without permission with direct user action.

The depth of the call chain may also matter since some older browsers requires permission is window.open isn’t called by the function that’s run immediately after a user action.

Therefore, we should call window.open within synchronous functions run as a result of direct user action to avoid the popup permission popup from showing in any browser.

We can check if a popup is blocked by checking if window.open returns null or undefined .

For instance, we can check if a popup window is blocked by writing:

const pop = (url, w, h) => {
  const popup = window.open(url, '_blank', 'toolbar=0,location=0,directories=0,status=1,menubar=0,titlebar=0,scrollbars=1,resizable=1,width=500,height=500');
  return popup !== null && typeof popup !== 'undefined'
}
console.log(pop('https://example.com'))

We call window.open with the url as the first argument and a string with some settings as the 3rd argument.

Then we return is popup isn’t null and popup isn’t undefined .

If the popup opens, then popup shouldn’t be null and it shouldn’t be undefined .

And so pop should return true if the popup opens.

Conclusion

We can avoid browser popup blockers by calling window.open in a synchronous function.