Categories
JavaScript Answers

How to get next / previous element using JavaScript?

To get next / previous element using JavaScript, we can use the nextSibling and previousSibling properties.

For instance, we write

<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>

to add 3 divs.

Then we write

document.getElementById("foo2").nextSibling;
document.getElementById("foo2").previousSibling;

to get the next and previous sibling of the div with ID foo2 with nextSibling and previousSibling.

Conclusion

To get next / previous element using JavaScript, we can use the nextSibling and previousSibling properties.

Categories
JavaScript Answers

How to remove auto slide on Bootstrap Carousel with JavaScript?

To remove auto slide on Bootstrap Carousel with JavaScript, we call carousel with an object.

For instance, we write

$(".carousel").carousel({
  interval: false,
});

to call carousel with an object that has interval set to false to disable auto slide on the Bootstrap carousel when creating it.

Categories
Vue Answers

How to pass props as initial data in Vue.js?

To pass props as initial data in Vue.js, we can set the prop value as an initial value of a reactive property.

For instance, we write

<script>
export default {
  //...
  props: {
    record: {
      type: Object,
      required: true,
    },
  },

  data() {
    return {
      recordLocal: { ...this.record },
    };
  },
  //...
};
</script>

to set the recordLocal reactive property to a copy of the record prop as its initial value.

We register the record prop in the props property.

Categories
JavaScript Answers

How to add the equivalent of the PHP strcmp() function with JavaScript?

To add the equivalent of the PHP strcmp() function with JavaScript, we can use the string localeCompare method.

For instance, we write

str1.localeCompare(str2)

to compare the values of str1 and str2 by their lexical order.

It’s aware of the locale the device is using when doing the comparison.

Categories
TypeScript Answers

How to do method overloading in TypeScript?

To do method overloading in TypeScript, we can add multiple signatures for the same method.

For instance, we write

class TestClass {
  someMethod(stringParameter: string): void;
  someMethod(numberParameter: number, stringParameter: string): void;
  someMethod(stringOrNumberParameter: any, stringParameter?: string): void {
    if (stringOrNumberParameter && typeof stringOrNumberParameter == "number") {
      //...
    } else {
      //...
    }
  }
}

to add the someMethod in TestClass that has multiple signatures.

We specify all the possible signatures for the method by adding the parameters and their types for each one.

And then we check the values of the parameters with if statements before we do anything with them.