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

Parsing unicode json data does not work properly in IE and Firefox

I am seeking to access JSON data files from another domain, specifically dealing with Unicode characters. For example: {"id":21,"name":"پرسپولیس تهران"} To achieve this, I have implemented a jQuery Ajax function as shown below: $.ajax({ ...

The functionality of Router.push() seems to vary depending on the timing

I'm attempting to utilize router.push() to modify the URL when the Search button is clicked. However, I've encountered a situation where this function only works sporadically. Ideally, after clicking the button, the user should be directed to the ...

How can I set up multiselect values in AngularJS ui-select?

Solution: Success! I managed to resolve the issue by implementing this solution and creating a customized build of the ui-select. Hopefully, this fix will be incorporated into the official master branch soon! Issue Is there a way to set up a select elem ...

What is the best way to notify the user if the percentage entered is not a numeric value?

My role is to notify the user when the entered value exceeds the acceptable range: if (document.myForm.outputPercentage.value <= 0 || document.myForm.outputPercentage.value >= 100) { alert( "Please enter a percentage between 1 and 100 ...

Material-UI Scroll Dialog that begins scrolling from the bottom

While attempting to incorporate a scrolling div with the ref tag inside Dialog Material-UI Design, I encountered an error stating Cannot read property 'scrollHeight' of undefined When running my code outside of the Dialog, it functions correctly ...

What is the process for moving information between files?

I have two files which are named as, employee-rates-controller.ts: private load() { return this.entityService .load(this.$scope.projectRevisionUid) .then(resp => { localStorage.removeItem('employeerates'); this.$ ...

Enhancing Website Design with Image Borders

I'm currently designing a website for a Media Agency and I'm looking to add a Frame-style border that gives the impression of being placed inside a television. The Television Image I have is a PNG file with a solid outer frame and a transparent i ...

Clicking on a radio button can trigger the selection of another radio button

I'm currently working on a form that includes 8 radio buttons - 4 for System A and 4 for System B. The options for the buttons are CF, ISO, ISO-B, and NW. My goal is to create a functionality where selecting a radio button in System A automatically se ...

Do I need to make any changes to the application when adding a new couchbase node to the cluster

Currently, I am utilizing the Node.js SDK to establish a connection with a couchbase cluster. Despite this, in the Node.js documentation, there is no clear instruction on how to input multiple IP addresses (of cluster nodes) when creating the cluster objec ...

Creating an interactive date selection feature with a calendar icon in MVC 5

I currently have a textbox that displays the datepicker when clicked. However, there is now a requirement to add a calendar icon inside the textbox. The datepicker should be displayed when either the calendar icon or the textbox is clicked. Below is the co ...

Transform gradient backgrounds as the mouse moves

I'm attempting to create a unique gradient effect based on the cursor position. The code below successfully changes the background color of the document body using $(document.body).css('background','rgb('+rgb.join(',')+&a ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

What is the best way to sum up all the values per month from a JSON file in React and showcase it as a single month using ChartJs?

Apologies if I didn't explain my question clearly enough. As a junior developer, sometimes it's challenging to ask the right questions, and I'm sure we've all been there, right? The data in my JSON file is structured like this: [ { &qu ...

implementing the CSS property based on the final value in the loop

I have created multiple divs with a data-line attribute. I am trying to loop through each div, extract the individual values from the data-line attribute, and apply them as percentages to the width property. However, it seems to only take the last value an ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

Creating a stylish button using a combination of CSS and Javascript classes within a webpage layout

Is it feasible to include a button in the layout that has HTML, CSS styles, and JavaScript functionality? For instance: This button is designed with both CSS styling and JavaScript classes. How can one incorporate CSS and JavaScript along with HTML conte ...

Is separating Jssor Slider CSS effective?

Having a bit of trouble with the Jssor slider here. I'm trying to separate the slider styles into an external CSS document and running into issues. For instance: <div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 11 ...

Simple chart with four sections in DimpleJS (D3)

Recently I decided to give DimpleJS a try for the first time with hopes of creating something like this: However, I seem to have run into some trouble. No matter what I do, nothing appears on the screen. http://jsbin.com/xosehedejo/1/edit window.onloa ...

Converting an OpenRasta XML request to JSON for response

I have a simple application using OpenRasta framework with a Home resource containing a single string property called Title (taken from the OpenRasta community documentation example). I've configured both XML and JSON data contracts for this resource ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...