Categories
JavaScript Answers

How to detect text change with Mutation Observer and JavaScript?

Sometimes, we want to detect text change with Mutation Observer and JavaScript?.

In this article, we’ll look at how to detect text change with Mutation Observer and JavaScript.

How to detect text change with Mutation Observer and JavaScript?

To detect text change with Mutation Observer and JavaScript, we can set the characterData option to true.

For instance, we write:

<div>

</div>

to add a div.

Then we write:

const mutate = (mutations) => {
  mutations.forEach((mutation) => {
    console.log(mutation);
  });
}

const target = document.querySelector('div')
const observer = new MutationObserver(mutate);
const config = {
  characterData: true,
  attributes: false,
  childList: true,
  subtree: false
};

observer.observe(target, config);

setTimeout(() => {
  target.textContent = 'hello world';
}, 1000);

We create a MutationObserver instance with the mutate function as the callback.

And we call observe with a config that has characterData set to true to observe text node changes.

Therefore, when we change the textContent of target to 'hello world', mutate would run.

Conclusion

To detect text change with Mutation Observer and JavaScript, we can set the characterData option to true.

Categories
JavaScript Answers

How to get child element from event.target with JavaScript?

Sometimes, we want to get child element from event.target with JavaScript.

In this article, we’ll look at how to get child element from event.target with JavaScript.

How to get child element from event.target with JavaScript?

To get child element from event.target with JavaScript, we can call querySelector on event.target.

For instance, we write:

<form>
  <div>
    <input />
  </div>
  <button type="submit">Submit</button>
</form>

to add a form with an input.

Then we write:

const form = document.querySelector('form')
form.onsubmit = (event) => {
  event.preventDefault()
  console.log(event.target.querySelector('input'));
}

to select the form with querySelector.

Next, we set form.onsubmit to a function that gets the input from the form with event.target.querySelector('input').

Since the submit event is triggered by the form, event.target is the form.

Conclusion

To get child element from event.target with JavaScript, we can call querySelector on event.target.

Categories
JavaScript Answers Vue Vue Answers

How to Set Up ESLint and Prettier in Vue.js 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:

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

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
  },
  extends: ["plugin:vue/essential", "eslint:recommended", "@vue/prettier"],
  parserOptions: {
    parser: "babel-eslint"
  },
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"
  },
  overrides: [
    {
      files: [
        "**/__tests__/*.{j,t}s?(x)",
        "**/tests/unit/**/*.spec.{j,t}s?(x)"
      ],
      env: {
        jest: true
      }
    }
  ]
};

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.

Categories
JavaScript Answers

How to select by object path with Lodash and JavaScript?

Sometimes, we want to select by object path with Lodash and JavaScript.

In this article, we’ll look at how to select by object path with Lodash and JavaScript.

How to select by object path with Lodash and JavaScript?

To select by object path with Lodash and JavaScript, we can use the get method.

For instance, we write:

const obj = {
  foo: 'bar',
  count: '3',
  counter: {
    count: '3',
  },
  baz: {
    test: "qux",
    tester: {
      name: "Ross"
    }
  }
};
const result = _.get(obj, 'baz.tester.name', 'defaultVal');
console.log(result)

We call get with the object we want to find the property value for, the path to the property value, and the default value returned when the property isn’t found respectively.

Therefore, result is 'Ross' since obj.baz.tester.name is 'Ross'.

Conclusion

To select by object path with Lodash and JavaScript, we can use the get method.

Categories
JavaScript Answers

How to get all keys of a deep object in JavaScript?

Sometimes, we want to get all keys of a deep object in JavaScript.

In this article, we’ll look at how to get all keys of a deep object in JavaScript.

How to get all keys of a deep object in JavaScript?

To get all keys of a deep object in JavaScript, we can recursive traverse the object to get the keys.

For instance, we write:

const obj = {
  foo: 'bar',
  count: '3',
  counter: {
    count: '3',
  },
  baz: {
    test: "qux",
    tester: {
      name: "Ross"
    }
  }
};

const objectDeepKeys = (obj, keys = []) => {
  for (const key of Object.keys(obj)) {
    keys.push(key)
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      objectDeepKeys(obj[key], keys)
    }
  }
  return keys
}

console.log(objectDeepKeys(obj))

to define the objectDeepKeys function that takes the obj object to traverse and the array of keys.

In the function, we loop through each key we get from Object.keys with a for-of loop.

And in the loop, we have keys.push(key) to append the key to keys.

If obj[key] is an object and it’s not null, we call objectDeepKeys to do the same thing in the next level.

As a result, we see ['foo', 'count', 'counter', 'count', 'baz', 'test', 'tester', 'name'] logged.

Conclusion

To get all keys of a deep object in JavaScript, we can recursive traverse the object to get the keys.