Categories
JavaScript Answers

How to replace CSS files on the fly with JavaScript?

To replace CSS files on the fly with JavaScript typically involves dynamically changing the href attribute of a <link> element that references the CSS file.

To do this we can write something like

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Replace CSS File on the Fly</title>
<link id="css-file" rel="stylesheet" type="text/css" href="original.css">
<script>
function replaceCSS(newCSSFile) {
    // Get the <link> element that references the CSS file
    const cssLink = document.getElementById('css-file');
    
    // Create a new <link> element
    const newLink = document.createElement('link');
    newLink.rel = 'stylesheet';
    newLink.type = 'text/css';
    newLink.href = newCSSFile;
    
    // Replace the old <link> element with the new one
    cssLink.parentNode.replaceChild(newLink, cssLink);
}
</script>
</head>
<body>
    <button onclick="replaceCSS('new.css')">Replace CSS</button>
</body>
</html>

In this example:

There’s a button in the body that, when clicked, calls the replaceCSS() function with the path to the new CSS file as an argument.

The replaceCSS() function retrieves the existing <link> element that references the CSS file by its ID (css-file). It creates a new <link> element with the provided path to the new CSS file.

It replaces the existing <link> element with the new one using the parentNode.replaceChild() method.

This approach allows you to dynamically replace CSS files on the fly using JavaScript. Keep in mind that replacing CSS files in this way may cause some flickering or re-rendering of the page as the new styles are applied.

Categories
JavaScript Answers

How to avoid decimal values in a number input with JavaScript?

To restrict a number input to accept only whole numbers (integers) without decimal values, you can use JavaScript to listen for the input event and validate the input value. Here’s an example of how you can achieve this:

<input type="number" id="myNumberInput">

to create an HTML input.

Then write the following JavaScript code

<script>
document.getElementById('myNumberInput').addEventListener('input', function(event) {
    // Get the input value
    let inputValue = event.target.value;
    
    // Remove any non-numeric characters and leading zeroes
    inputValue = inputValue.replace(/\D|^0+/g, '');
    
    // Update the input value
    event.target.value = inputValue;
});
</script>

In this code we attach an event listener to the number input element with the ID myNumberInput.

When the input event is triggered (i.e., when the user types or pastes into the input field), the event listener function is called.

Inside the event listener function, we retrieve the input value from the event object.

We use a regular expression (/\D|^0+/g) to remove any non-numeric characters and leading zeroes from the input value.

Finally, we update the input value to the sanitized value without decimal values.

This code will ensure that only whole numbers are accepted in the number input field, and any decimal values will be automatically removed as the user types.

Categories
JavaScript Answers

How to open a link in a new tab with JavaScript in a Chrome extension?

In a Chrome extension, you can open a link in a new tab using JavaScript by leveraging the chrome.tabs.create() method provided by the Chrome extension API. Here’s how you can do it:

javascript Copy code // Example code to open a link in a new tab chrome.tabs.create({ url: “https://example.com”, active: true }); This code snippet will open a new tab with the URL “https://example.com”. The active: true option ensures that the newly opened tab becomes the active tab.

Make sure to include this code within your Chrome extension’s background script, popup script, or content script, depending on where you want the link to be opened from.

For instance, if you want to open a link in a new tab when a user clicks on a browser action icon (popup), you can include this code in your popup script.

First we write the following JavaScript

document.addEventListener('DOMContentLoaded', function() {
  const link = document.getElementById('myLink');
  link.addEventListener('click', function() {
    chrome.tabs.create({ url: "https://example.com", active: true });
  });
});

Then we write the following HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Popup</title>
  <script src="popup.js"></script>
</head>
<body>
  <a href="#" id="myLink">Open Example.com in New Tab</a>
</body>
</html>

This code creates a popup with a link. When the user clicks on the link, the chrome.tabs.create() method is called to open “https://example.com” in a new tab.

Categories
JavaScript

What’s New in ES2022?

The following new fearures be included in ES2022.

String.prototype.replaceAll()

This method replaces all occurrences of a substring within a string with another substring. Prior to this, you had to use regular expressions or iterate through occurrences manually.

To use it, we can write something like:

const str = 'foo bar foo baz';
const newStr = str.replaceAll('foo', 'qux');
console.log(newStr); // Output: 'qux bar qux baz'

Promise.any()

This method returns a single Promise that resolves as soon as any of the provided promises resolves, or rejects if all of the provided promises are rejected.

To use it, we can write something like:

Promise.any([promise1, promise2, promise3])
    .then((value) => {
        console.log(value); // Output: value of the first resolved promise
    })
    .catch((error) => {
        console.error(error); // Output: AggregateError containing errors of all rejected promises
    });

WeakRefs

Weak references allow you to hold references to objects without preventing them from being garbage collected. This can be useful in scenarios where you need to keep track of objects without preventing their natural cleanup.

Numeric Separators: Numeric separators allow you to make numeric literals more readable by inserting underscores (_) between groups of digits.

For example we write

const billion = 1_000_000_000;
const binary = 0b1010_0001_1001_0000;

Promise.allSettled()

This method returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describes the outcome of each promise.

To use it, we can write something like

Promise.allSettled([promise1, promise2, promise3])
    .then((results) => {
        console.log(results);
    });
Categories
JavaScript Answers Vue Vue Answers

How to Set Up ESLint and Prettier in Vue.js 3 Projects and Format Code Automatically with Prettier with VS Code?

Sometimes, we want to set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code.

In this article, we’ll look at how to set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code.

How to Set Up ESLint and Prettier in Vue.js Projects and Format Code Automatically with Prettier with VS Code?

To set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code, we install a few packages and VS Code extensions and change a few settings.

First, we install a few packages into our Vue project by running:

npm i -D babel-eslint eslint eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-prettier

We install the ESLint with plugins for Vue projects.

Then we install extensions by pressing ctrl+shift+p in VS Code and search for ‘Extensions: Install Extension’.

Next, in the extensions search box on the left, we search for Prettier, ESLint, and Vetur and install them by clicking install.

After that, we press ctrl+shift+p in VS Code and search for ‘Preferences: Open Settings (JSON).

And then we paste the following into settings.json:

{
  "[css]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "files.eol": "\n",
  "files.trimTrailingWhitespace": true,
  "editor.renderControlCharacters": false,
  "editor.renderWhitespace": "none",
  "javascript.updateImportsOnFileMove.enabled": "always",
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
  },
  "[jsonc]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
  },
  "[html]": {
    "editor.defaultFormatter": "vscode.html-language-features",
    "editor.formatOnSave": true
  },
  "[scss]": {
    "editor.defaultFormatter": "sibiraj-s.vscode-scss-formatter",
    "editor.formatOnSave": true
  },
  "typescript.updateImportsOnFileMove.enabled": "always",
  "html.format.wrapLineLength": 80,
  "files.insertFinalNewline": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
  },
  "editor.formatOnSave": true,
  "vetur.format.defaultFormatter.html": "js-beautify-html",
  "[vue]": {
    "editor.defaultFormatter": "octref.vetur"
  },
  "editor.tabSize": 2,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[python]": {
    "editor.formatOnType": true
  },
  "extensions.ignoreRecommendations": true,
  "vue.codeActions.savingTimeLimit": 2000
}

to enable auto formatting and linting of Vue projects.

Finally, we create an .eslintrc.js file in the Vue project’s root and add:

module.exports = {
  root: true,
  env: {
    node: true,
    es2022: true,
  },
  extends: ["eslint:recommended", "plugin:vue/vue3-recommended", "prettier"],
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
  },
};

into the file to enable the extensions needed for auto linting and formatting.

Conclusion

To set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code, we install a few packages and VS Code extensions and change a few settings.