Categories
JavaScript Answers

How to position a DIV in a specific coordinates with JavaScript?

To position a DIV in a specific coordinates with JavaScript, we set the left and top properties.

For instance, we write

const d = document.getElementById("yourDivId");
d.style.position = "absolute";
d.style.left = "10px";
d.style.top = "20px";

to select the element with getElementById.

We set its position to 'absolute'.

And then we set the left and top position to shift it horizontally and vertically.

Categories
JavaScript Answers

How to append to innerHTML without destroying descendants’ event listeners with JavaScript?

To append to innerHTML without destroying descendants’ event listeners with JavaScript, we need to use DOM methods.

For instance, we write

<div id="myDiv">
  <span id="mySpan">foo</span>
</div>

to add the div and span.

const mySpan = document.getElementById("mySpan");
mySpan.onclick = () => {
  alert("hi");
};

const myDiv = document.getElementById("myDiv");
myDiv.appendChild(document.createTextNode("bar"));

to get the span with getElementById.

And we add a click listener to it by setting the onclick property to the click listener.

Then we get the div with getElementById and then call appendChild on it to append a text node as its last child.

We create the text node with createTextNode.

Then span’s click listener is kept after we call appendChild.

Categories
JavaScript Answers

How to get element at specified position with JavaScript?

To get element at specified position with JavaScript, we use the elementFromPoint method.

For instance, we write

const elem = document.elementFromPoint(2, 2);

to call document.elementFromPoint with the coordinate of the element to get to return the element at the coordinates.

Categories
JavaScript Answers

How to download a PDF file instead of opening them in browser when clicked with HTML?

To download a PDF file instead of opening them in browser when clicked with HTML, we add the download attribute.

For instance, we write

<a href="dummy.pdf" download="filename.pdf">download</a>

to add the download attribute and set it to the file name of the downloaded file to make the file download instead of opening it.

Categories
JavaScript Answers

How to change element style attribute dynamically using JavaScript?

To change element style attribute dynamically using JavaScript, we call the style.setProperty method.

For instance, we write

document.getElementById("abc").style.setProperty("padding-top", "10px");
document
  .getElementById("abc")
  .style.setProperty("padding-top", "10px", "important");

to select the eleemnt with getElementByid.

And then we call style.setProperty with the property name, value, and optionally, the 'important' string as the 3rd argument.

"important" adds the !important directive.