The issue with the functionality of position absolute in CSS when used with JavaScript

<html>
<head>
<style>

#wrapper{
position: absolute;
   top : 250px;
    width: 500px;
    height: 500px;
    border: 1px solid red;
}


.tagging{
position: absolute;  
   border: 1px solid black;
   width : 20px;
   height: 30px;


}


</style>
<script>
window.onload = function(event){
     var wrapper =  document.getElementById("wrapper");

     var wrapperOffsetTop = wrapper.offsetTop;


     wrapper.onmousedown = function(event){

          var div = document.createElement("div");
          div.className = "tagging";
         div.style.top = event.clientY  - wrapperOffsetTop;
         wrapper.appendChild(div);

     }
}
</script>

</head>
<body>
<div id="wrapper">

</div>
</body>
</html>

I have developed a simple application where users can click on the area to append a box with the cursor position. However, it seems that the functionality is not working as expected.

After making some adjustments and adding +"px", the code worked perfectly for me.

But in my real-world application, the same approach does not seem to work as intended:

<html>
<head>
<style>
.tagging{
    border: 1px solid red;
    position: absolute; 
    padding: 0px;
    margin: 0px; 
    width : 20px;
    height: 20px;

}
</style>
<script>
  window.onload = function(){

      //get Information about imgWrapper
     var imgWrapper = document.getElementById("imgwrapper");
     var wrapperOffsetTop = imgWrapper.offsetTop;
     var wrapperOffsetLeft = imgWrapper.offsetLeft;


  //set the image wrapper to be the same size as the image
     var img = document.getElementsByTagName('img');
     imgWrapper.style.width = img[0].width;

     //when image wrapper is clicked, append a div element
     img[0].onmousedown = function(event) {
       event.preventDefault();

       //create tag with class
       var div = document.createElement("div");
       div.className = "tagging";
        imgwrapper.appendChild(div);

        //get the position of mouse cursor
         var mouseX = event.clientX;
         var mouseY = event.clientY;

       //set the position of the div
        div.style.top =  (mouseY - wrapperOffsetTop) + "px";
        div.style.left  = (mouseX - wrapperOffsetLeft) + "px";  

 }};</script>;
</head>
<body>
<div id="imgwrapper">
<img src="jlin.jpg">
</div>
<form action="./yipee.php" method="POST" id="noob">
<input type="submit">
</form>
</body>
</html>

Answer №1

When setting the top property, make sure to include units such as pixels or percentages instead of just a number value.

element.style.top = (event.clientY - offsetTop) + "px";

Answer №2

UPDATE: Originally, the code was functioning well on Firefox and Chrome. However, to ensure compatibility with IE8, which does not support the W3 DOM event object, you must utilize the window.event as a fallback. if (!event) { event = window.event; }

Unless I have misinterpreted your query, an adjustment needs to be made to include an offset for the Left Margin:

<html>
<head>
<style>

#wrapper{
position: absolute;
   top : 250px;
    width: 500px;
    height: 500px;
    border: 1px solid red;
}


.tagging{
position: absolute;  
   border: 1px solid black;
   width : 20px;
   height: 30px;


}


</style>
<script>
window.onload = function(event){
     var wrapper =  document.getElementById("wrapper");

     var wrapperOffsetTop = wrapper.offsetTop;
     var wrapperOffsetLeft = wrapper.offsetLeft;


     wrapper.onmousedown = function(event){

          if (!event) {
              event = window.event;
          }
          var div = document.createElement("div");
          div.className = "tagging";
         div.style.top = event.clientY  - wrapperOffsetTop;
         div.style.left = event.clientX  - wrapperOffsetLeft;
         wrapper.appendChild(div);

     }
}
</script>

</head>
<body>
<div id="wrapper">

</div>
</body>
</html>

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

Changing Image Size in Real Time

Trying to figure out the best way to handle this situation - I need to call a static image from an API server that requires height and width parameters for generating the image size. My website is CSS dynamic, adapting to different screen sizes including ...

Why doesn't the z-index of child elements function properly when their fixed parents share the same z-index value?

I have utilized jsfiddle to replicate my problem. My goal is to position .top .inside above .bottom .inside. I am aware that z-index only functions within its respective position type, for example fixed and absolute do not share the same z-index level. How ...

Tips for referencing a function declared within a prototype

I have been attempting to enhance a web page by adding functionality using a jquery library that lacks documentation. The problem I am encountering is primarily due to my lack of understanding of the jquery plugin model and/or the inner workings of javascr ...

The text manipulates the canvas position and changes the location of mouse hover interaction

I am trying to achieve a similar header layout like the one shown on this page. However, when I insert some text within the header section: <div id="large-header" class="large-header"> <h1 style="font-size:150%;">Dummy Text</h1> ...

Tips for transferring client-side data to the server-side in Angular, Node.js, and Express

Seeking a straightforward solution to a seemingly basic question. I am utilizing Angular's $http method with a GET request for a promise from a specific URL (URL_OF_INTEREST). My server runs an express script server.js capable of handling GET reques ...

Link the Material-ui ToggleButtonGroup with redux-form

I'm currently facing a challenge with connecting the material-ui ToggleButtonGroup to Redux form. The issue seems to be occurring in my code snippet below: <Field name='operator' component={FormToggleButtonGroup} > <ToggleButt ...

Modifying dynamic input fields based on the selected input field type

Seeking advice on a challenge I'm facing while testing a website. My task is to mask input fields in screenshots after executing tests because we share data with other teams. I've tried using JS before the script by changing the input type to &ap ...

Is there a way to dynamically import a JSON file within an ECMAScript module?

Currently, I am attempting the following in my code: let filePath = '../../data/my-file.json' import inputArray from filePath assert { type: 'json' } The outcome of this operation is as follows: file:///.../script.mjs:5 import inputArr ...

encountering difficulty with loading JavaScript code while customizing form fields in Symfony/Sonata Admin

I have been attempting to personalize a field in a form created with the Sonata Admin Bundle. I followed the solution provided in this article: Customize form field rendering. Apart from customizing the form field, I also aimed to implement an autocomple ...

Executing JavaScript in HttpClient or HtmlUnitHow to trigger javascript in HttpClient or HtmlUnit

Currently, I am using the HttpClient POST method to perform a specific action on a website. This involves using Javascript for an ajax connection which generates a unique requestID in the form of var reqID = Math.floor(Math.random()*1000001);. I need to ac ...

MongoDB does not treat aggregate match pipeline as equal to in comparisons

I've been tackling an aggregate pipeline task for MongoDB where I need to retrieve items that do not have a specific user ID. Despite my efforts, I'm struggling to get it right. I attempted using $not, $ne, and $nin in various ways but couldn&ap ...

Restrict the character count in the input field according to its width

Is there a way to restrict the number of characters in an input field based on its width? I have a dynamic input field with varying widths and I would like users to be able to type without their text extending outside of the input boundary. Using maxLeng ...

The spotlight is shifting towards validating a datepicker field using jQuery

I am currently working on validating a datepicker field using jQuery. However, whenever I try to validate it, the calendar popup opens up. I only want to display the validation message without the datepicker popup. ...

Unlocking the Power of ReactJS: Passing Values in Material UI for Advanced JSON Structures

How can I access complex objects in the GRID component of material UI? Specifically, I am trying to access the ami_info.account, but it only displays Undefined in the UI. var columns = [ { field: 'id', headerName: 'ID', width: 90, ...

Flexibility on smaller screens using Flexbox

On larger screens, I have arranged 4 icons in a row, but on smaller screens (less than 768px), I need to display only 2 icons in a row. This is my current code : .welcome { display: flex; justify-content: space-around; } @media (max-width: 768px) ...

What is the optimal method for iterating through every element in a string array?

Within my code, I am dealing with an array named var mya = ["someval1", "someotherval1", "someval2", "someval3"];. The goal is to have a function that receives an object with a property set to one of these values. Instead of simply iterating over the arra ...

Navigating to JSON input in Express correctly

I have successfully created a basic Express-based API to serve JSON data, but now I want to enhance its functionality. The JSON file follows this structure: (some sections are excluded) [{ "ID": "1", "NAME": "George Washington", "PAGE": "http://en.w ...

Using NodeJS and Express: redirection fails to load the specified endpoint

My current project involves a simple e-commerce web application running on localhost built with nodejs and express. Admins are required to register in order to gain access to functionalities such as adding, editing, and removing products from the product l ...

Implementing a Basic jQuery Animation: How to Easily Display or Conceal DIV Elements Using fadeIn and fadeOut

SCENARIO: Include 2 links, MY INFO and LOG IN, within a list of ul, li elements. Hovering over one link should display a box with a form inside using the fadeIn animation. The other link should show a button in a box with a fadeIn animation when hovered o ...

What steps can be taken to enable users to draw a path on a Google Map?

I'm working on a new project for a Facebook app that will allow users to map out their marathon route using Google Maps. I plan to utilize mySQL database records to store fixed points along the path (such as specific locations based on latitude and lo ...