Am I on the right track in my understanding of how document and viewport relate to mouse position in JavaScript?

After reviewing responses from a previous inquiry, it is evident that both pertain to the x and y coordinates of mouse positions.

  • In relation to the document and
  • In relation to the viewport.

I have delved into an article on QuirksMode, yet I feel there might be missing elements from my comprehension. To aid in my understanding, I prepared these two diagrams. Would appreciate validation of my analysis?

If we scroll the document by 250px...

Answer №1

Your analysis is spot on (and I must say, those diagrams are quite impressive!)

However, in regards to your previous post, there seems to be an excess of information provided.

The key concept to grasp here is the relationship between the document and viewport. The document remains fixed while the viewport moves along with you, having a scroll offset.

In theory, you have the option to position your dialog window relative to either of these elements. Let's imagine the dialog as a simple division element:

<body>
<button id="save">Save</button>
<div id="dialog" style="position:absolute;">Are you sure?</div>
</body>

If you wish to position that element in relation to your button when clicked, you could utilize the document:

<script>
document.getElementById("save").onclick = function(e) {
  var dialog = document.getElementById("dialog");

  dialog.style.top = e.pageY + "px";
  /*
  The pageY value indicates the mouse position relative to the
  document at the time of this event.
  */
};
</script>

Alternatively, you could opt for utilizing the viewport:

<script>
document.getElementById("save").onclick = function(e) {
  var dialog = document.getElementById("dialog");

  dialog.style.top = e.clientY + window.pageYOffset + "px";
  /*
  Here, clientY provides the mouse position relative to
  the viewport during this event, while pageYOffset
  represents the user's scroll distance.
  */
};
</script>

Another approach would involve using the button itself. This method ensures a consistent position regardless of where exactly the user clicks:

<script>
document.getElementById("save").onclick = function(e) {
  var dialog = document.getElementById("dialog");

  dialog.style.top = document.getElementById("save").offsetTop + "px";
  /*
  Utilizing offsetTop gives the button's position relative to its nearest
  positioned ancestor. For deeply nested elements, additional calculations may be required.
  (jQuery's "offset" method handles this automatically).
  */
};
</script>

For applying the last method with jQuery's dialog class, you can simply follow this procedure:

<script>
  $("#save").click(function(e) {
    $("#dialog").dialog({
      position: {
        my: "top",
        at: "bottom",
        of: $("#save")
      }
      /*
      Refer to: http://docs.jquery.com/UI/API/1.8/Position
      */
    });
  });
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styling with CSS: Enhancing list items with separators

Is there a way to include a separator image in my list using CSS? li { list-style: none; background-image: url("SlicingImage/button_unselect.png"); height: 53px; width: 180px; } This is the code for the separator image: url("SlicingImage ...

How to access the ID value from the URL within a different component that was passed as a prop in

I have a scenario where I am building a reusable component with two child components in the following flow: Child Component 1 -> Parent Component -> Super Parent Main Component In the child component, I define a prop called 'url' which is ...

I'm having trouble pinpointing the issue in my code

For some reason, the first button in the div in this code is not working on HTML files. I have tried multiple JavaScript and HTML validators but none of them seem to work. Surprisingly, it works fine on codecademy.com and w3schools.com, but the issue persi ...

No definition found for state

Currently, I am facing an issue while trying to fetch data from an API, set it on my State, and display that state in a table. The problem arises because the render method is called first, causing my state to be undefined which leads to this specific issue ...

Using the Croppie plugin to crop an image before uploading via jQuery Ajax in PHP

I've successfully implemented a code snippet that allows image cropping using PHP, jQuery, and Ajax with the Croppie plugin. Currently, I'm facing an issue while trying to include additional input values along with the image upload process. I ...

Creating an AngularJS directive specifically for a certain <div> tag

Recently, I began learning angularjs and came across a script to change the font size. However, this script ended up changing all <p> tags on the entire webpage. Is there a way to modify the font size of <p> tags only within the <div class=" ...

What is the process for implementing a click event and accessing the DOM within an iframe using react-frame-component?

I am working on using the react-frame-component to create an iframe. I am trying to bind a click event on the iframe and retrieve the DOM element with the id of "abc" inside the iframe. Can anyone guide me on how to achieve this? The code snippet provided ...

Generating an array of keys from duplicated values in Typescript

My data is structured in the following array format: { itemTitle: 'value example', itemType: 'value example', itemDescription: 'value example', itemFamily: 'Asset', }, { itemTitle: 'val ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

When you zoom in or out, HTML5 elements styled with CSS will dynamically adjust

Hey everyone, I have a question about a problem I'm facing with my HTML and CSS page. The issue is that when I zoom in, the "Section" part moves underneath the nav bar, and when I zoom out, the footer moves next to the section part... Below is a sni ...

Can you provide an example and explain the functions `getOptionSelected` and `getOptionLabel` in Material UI?

While going through the Mui Documentation, I came across the Autocomplete component section and found two interesting props: getOptionLabel and getOptionSelected. Although I read their definitions, I'm still struggling to grasp them fully. Can someone ...

Error encountered when attempting to utilize a variable within an EJS template document

I seem to be encountering some difficulties while attempting to get an EJS template file to recognize a variable that holds the rows from an SQLite3 table query in a related .js file. Whenever I try to access that route by launching the server, I receive a ...

Ways to eliminate the final empty space in a grid

Looking to create a layout with 5 boxes? Currently, I have managed to set up the grid structure, but the issue is that there is still some space below the last item in the grid. Below is the styled component for Container: const Container = styled('di ...

Converting a JavaScript array to formData

Struggling with sending an array via Ajax to PHP. For more information, visit jsfiddle https://jsfiddle.net/CraigDavison/9spyn7ah/ function autoPopulate() { var cast = "John Wayne, Julia Roberts, Kevin Spacey"; cast = cast.split(', '); ...

In IE8, a border is applied to the max-width property when the width is set to

I'm attempting to design a box that adjusts in size according to the parent container, utilizing a mix of max-width and width:100%. With this setup, the box's width is determined by the max-width property, ensuring it shrinks within its boundari ...

What is the best way to rearrange images within a grid container?

I apologize for asking numerous questions, but could someone please guide me on how to position an image slightly to the right of center or just 1 inch to the left of center? http://jsfiddle.net/96d7udd7/ Below is the HTML code snippet: <figure class ...

The bookdown feature of tufte_html_book, when combined with the csl style, struggles to properly position citations

bookdown::tufte_html_book does not place citations in the margin with csl notes. Here is an example: bookdown::render_book(input = "index.rmd", output_format = "bookdown::tufte_html_book") The csl used comes from: https://raw.githu ...

Tips on updating arrow button icon when clicked using jquery

I am currently working on a project where I have a button icon that I want to change upon clicking it. I am using the following jQuery code: <script> $('div[id^="module-tab-"]').click(function(){ $(this).next('.hi').sl ...

When adding text to a React Material UI Box, it can sometimes extend beyond the boundaries

I'm currently working on a straightforward React page, but I've encountered an issue right from the start: my text is overflowing the box and I can't figure out why. Could someone take a look at my styles? Here's a picture showing the ...

React: The peculiar contradiction of useEffect with eventHandler props

Having trouble with this specific example. The issue arises with an Input component that includes an onChange prop to manage internal data changes. Under normal circumstances, if the value is updated externally, the onChange prop does not trigger since t ...