Categories
JavaScript Answers

How to send a JSON object using HTML form data with JavaScript?

To send a JSON object using HTML form data with JavaScript, we use fetch.

For instance, we write

const ajax = async (config) => {
  const request = await fetch(config.url, {
    method: config.method,
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(config.payload),
  });
  response = await request.json();
  console.log("response", response);
  return response;
};

to call fetch with the URL to make the request to and an object with the headers and body.

We set body to the stringifed JSON object we get with JSON.stringify to send that as the JSON body.

We set the headers to the request headers keys and values.

Then we get the JSON response in a promise with request.json.

Categories
JavaScript Answers

How to detect “shift+enter” and generate a new line in text area with JavaScript?

To detect "shift+enter" and generate a new line in text area with JavaScript, we check the keys pressed in the keyup event handler.

For instance, we write

if (event.keyCode === 13 && event.shiftKey) {
  console.log("Shift+Enter key Pressed");
}

to check if enter is pressed by checking if keyCode is 13.

And we check if shift key is pressed with shiftKey.

If both are true, then shift+enter is pressed.

Categories
Angular Answers

How to scroll to element on click in Angular and TypeScript?

To scroll to element on click in Angular and TypeScript, we call the scrollIntoView method.

For instance, we write

<button (click)="scroll(target)">Scroll To Div</button>
<div #target>Your target</div>

to add a button and a div in the template.

Then we write

//...
export default class Component {
  //...
  scroll(el: HTMLElement) {
    el.scrollIntoView();
  }
}

to add the scroll method into the Component component.

We call el.scrollIntoView to scroll to the el element, which is the div.

Categories
JavaScript Answers

How to get and set the current web page scroll position with JavaScript?

To get and set the current web page scroll position with JavaScript, we set the scrollTop property.

For instance, we write

document.documentElement.scrollTop = document.body.scrollTop = 1000;

to set the scrollTop property of the body element to 1000 to scroll 1000px down.

Categories
JavaScript Answers

How to append HTML string to the DOM with JavaScript?

To append HTML string to the DOM with JavaScript, we create an element with the HTML inside.

For instance, we write

const child = document.createElement("div");
child.innerHTML = str;
child = child.firstChild;
document.getElementById("test").appendChild(child);

to create the div with createElement.

And then we set its innerHTML property to the HTML string str.

Next, we get the first chilld of the div with firstChild.

And then we call appendChild to append the child as the last child o the element with ID test.