Categories
JavaScript Tips

JavaScript Tips — Disabling Divs, Dynamic Script Elements, and More

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

How to Disable all div Content

We can use the pointer-events: none style to disable mouse interaction on a div element.

Therefore, we can write the following code to disable interaction on a div with JavaScript:

$("div").addClass("disabled");

Then the disabled class would have the following styles:

.disabled {  
  pointer-events: none;  
  opacity: 0.5;  
}

We disable mouse interaction and also make the div content translucent.

Reject the Promise with the async-await syntax

If we want to reject the promise returned by an async function, we can throw an error or use Promise.reject .

For instance, we can write:

const asyncFn = async () => {  
  try {  
    const val = await foo();  
    //...  
  }  
  catch(error) {  
    throw new Error('error');  
  }  
}

Then the returned promise is rejected with the reason 'error' .

Likewise, we can use Promise.reject by writing:

const asyncFn = async () => {  
  try {  
    const val = await foo();  
    //...  
  }  
  catch(error) {  
    return Promise.reject(new Error('error'));  
  }  
}

In the catch block we return a promise that’s rejected with the Promise.reject method.

We still pass in the Error instance with the reason 'error' .

Calculate Yesterday’s Date in JavaScript

We can calculate yesterday’s date with the getDate method to return the day of the month

Then we subtract 1 from it and pass it into the setDate method.

To do that, we write:

const date = new Date();  
date.setDate(date.getDate() - 1);

Append <script> Element

To append a script element dynamically to the DOM, we can call createElement to create an element.

Then we can call appendChild to append the newly created script element.

For example, we can write:

const script = document.createElement("script");  
script.type = "text/javascript";   
script.text = "console.log('hello');"  
document.body.appendChild(script);

We created a script with inline code.

Then we called appendChild to append the script.

Also, we can write the following to append a linked script:

const script = document.createElement("script");  
script.type = "text/javascript";   
script.src   = "/script.js";  
document.body.appendChild(script);

We append script.js to set the path of the script.

Everything else is the same.

Get the Coordinates of a Mouse Click on a canvas Element

To get the coordinate of a mouse click on a canvas element, we can use the clientX and clientY properties.

For instance, we can write:

const getCursorPosition = (canvas, event) => {  
  const rect = canvas.getBoundingClientRect();  
  const x = event.clientX - rect.left;  
  const y = event.clientY - rect.top;  
  console.log(x, y);  
}

We can use the getBoundingClientRect method to get the left and top offsets of the canvas.

We subtract them from clientX and clientY respectively to get the coordinate of the mouse in the canvas.

Then we can use this function by writing:

const canvas = document.querySelector('canvas')  
canvas.addEventListener('mousedown', (e) => {  
  getCursorPosition(canvas, e)  
})

Check if a JavaScript String is a URL

We can use the URL constructor to check if a JavaScript string is a valid URL.

For instance, we can write:

const isValidUrl = (string) => {  
  try {  
    new URL(string);  
  } catch(e) {  
    return false;    
  }  
  return true;  
}

We try to create a URL instance to see if it’s a URL.

If it is, then no exception would be thrown and we return true .

Otherwise, we return false in the catch block since an exception would be thrown when the URL constructor tries to parse an invalid URL string.

Use encodeURI or encodeURIComponent for Encoding URLs

encodeURI assumes that the input is a complete URI that we’re passing in as the argument.

encodeURIComponent encoded everything with a special meaning.

For instance, we can write:

encodeURIComponent('&');

and returns “%26” .

And we can write:

encodeURI('http://example.com/?foo= bar')

and get “http://example.com/?foo=%20bar" .

Conclusion

We can disable div interactivity with some CSS.

There are 2 ways to return a rejected promises in an async function.

The URL constructor takes the hard work out of parsing URL strings.

Script tags can be dynamically inserted.

We can check a mouse position on a canvas with some properties.

Calculating yesterday’s date can be done with the Date instance methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *