Is the absolute positioned element on the left or right based on its current location?

Is there a way to assign absolute positioning with left at 0px or right at 0px depending on whether the positioned div will go outside of its container?

For example, when you right click in a browser and see the menu appear to the right of where you clicked, it doesn't go all the way to the edge of the page. Instead, it stays within the visible area.

Here's an example for illustration (Hover over boxes): http://jsfiddle.net/ueSNQ/1/

Answer №1

It appears that a solution involving scripting will be necessary to address the issue of an absolutely positioned div potentially extending beyond its container. While IE does support CSS expressions, you are likely seeking a cross-browser-compatible approach.

With that said, resolving this issue should involve implementing something along these lines:

function isOverflow(parent, child){
    var left = 0;
    var op = child;
    while(op && op != parent){
        left += op.offsetLeft;
        op = op.offsetParent;
    }

    return ((left + child.offsetWidth) > parent.offsetWidth);

}

function getHoverHandler(parent, child){
    return function(){
        if(isOverflow(parent, child)){
            child.style.marginLeft = 'auto';
            child.style.right = '0px';
            child.style.left = '';
        }
    }
}

function attach(o,e,f){
    if(o.addEventListener){
        o.addEventListener(e, f, false);
    }else if(o.attachEvent){
        o.attachEvent('on'+e,f);
    }
}

var yellowElement = document.getElementsByTagName('UL')[0];
var list= document.getElementsByTagName('LI');
for(var i = 0; i < list.length; i++){
    var element = list[i];
    var tip = element.getElementsByTagName('DIV')[0];
    attach(element, 'mouseover', getHoverHandler(yellowElement,tip));

}

Answer №2

Hello there, Below are some steps you can try:

1. Start by having a container div. When right-clicking on it, show another div containing a list of menus.
2. Create variables for the left position of the container div (**contLeft**) and its width (**contWidth**).
3. Set the oncontextmenu event handler on the container div.
4. In the event handler function, store the mouse x position in **mosX** and the mouse y position in **mosY**. Position the displayed div with top as mosY and left as mosX.
5. To keep the div within the container, calculate the overall screen space occupied by the container as **totPos = (contLeft + contWidth)**.
6. Determine the screen space taken up by the menu div as **posMenu = (mosX + width of div)**.
7. If totPos is equal to or greater than posMenu, display the menu at the same top and left location using the values of mosY and mosX.
8. Otherwise, place the menu at top = mosY and left = (mosX - width of menu div).

I hope these instructions help resolve your issue.

Answer №3

Primarily, when the container div has a specified position, position: absolute, right: 0px or left: 0px will be relative to the container's position. If not set, it will align with the nearest parent node in the hierarchy that has a defined position. Failing this, it will default to being relative to the body element. To pinpoint the appropriate ancestor with a set position, you must search up the chain of parent and grandparent containers. For clarification/examples, feel free to provide additional details for better assistance.

UPDATE:

Upon reviewing your provided example, it appears to mirror the scenario outlined in my initial response. Consider calculating the offsetWidth values of the parent element, adjusting the left attribute to prevent overflowing content. Alternatively, removing the left positioning and setting the right value can achieve the desired alignment. Ensuring consistent width and height adjustments may require considering corner cases for optimal results.

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

Display or conceal the nearest element that was clicked

http://jsfiddle.net/KevinOrin/xycCx/1/ jQuery('.happening-main-text .readmore').click(function() { jQuery('.divmore').toggle('slow'); return false; }); ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

Detecting letter case and text input in an HTML form can be done by using

I am looking to format a question along with multiple options in a text box, similar to how it is done in a Word file or plain text. Once saved, I want the questions to be displayed in a list and the options organized in a table. How can I extract the ques ...

Seeking help with h2 headings, nested hyperlinks, and clickable images

Attempting to tackle a homework question today. This is the task at hand.... List a variety of foods in the following categories: Sandwiches, Drinks, Desserts. Use h2 tags to create these categories. Under each category, create a nested list that inc ...

How can I convert a string containing integers into an int[] using javascript or jQuery?

I want to create a feature that allows users to input a list of IDs in a textarea, with the option to separate them by either whitespace or commas. After the user inputs the list, I need to convert it into an int[] array but also throw an error if the str ...

What could be causing the issue with my Date and Time input not functioning correctly?

I developed a React frontend application styled with Material UI design. The issue I am facing is that after adding the Date and Time component styling to the form, it is unable to process the "name" value for posting. Specifically, the error message "Ty ...

Collecting, gathering content repeatedly

Hey there, just checking in. I'm currently working on extracting information related to CEO Pay Ratio and compiling links to this section for processing by a function. My goal is for the function to capture content starting from a specified tag and en ...

document ready function in the Microsoft AJAX client side library

The Microsoft AJAX client-side library contains various functions that imitate the server-side Page Life Cycle and conditions like if (!Page.IsPostBack). I am unsure about which client-side function corresponds to the equivalent server-side method. What is ...

Divide the webpage into four equal sections, each showcasing distinct information sourced from the database

Is there a way to divide my page into 4 sections with data from a database source? Currently, I am displaying the data from the database in a single table, but I would like to split it into four parts, each showing different results from the database. Ad ...

Preserve the custom hook's return value in the component's state

I am currently facing a challenge in saving a value obtained from a custom hook, which fetches data from the server, into the state of a functional component using useState. This is necessary because I anticipate changes to this value, requiring a rerender ...

Change the <base> element programmatically during server-side rendering

Searching for a way to obtain the base URL for an HTML page, so that relative URL requests from the browser utilize that base. If you are looking for answers, check out this link: Defining root of HTML in a folder within the site root folder When serving ...

Locating the jQuery element just one element next to it

Having set up my HTML like this. <div id="wrap"> <div class="left"></div> <div class="right"> <a href="#">link</a> </div> <div class="listings" style="display:none"> <ul> ...

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

Using jQuery to drag a div and drop it to swap out an image in a different

I am looking to implement a drag and drop function where I can move elements from one div to another, each containing different images. However, I want the image displayed in the second div to change based on the element being dragged. For example: When d ...

Ways to run evaluations on 'private' functions within an angular service using Karma and Jasmine

In my Angular application, I have a BracketService that consists of various functions for comparing weights and creating brackets based on weight groups. The service includes functions like compareByWeight, filterWeightGroup, and createBracketsByWeightGrou ...

Is it possible to utilize a JSON file to input events into FullCalendar that can accommodate multiple users?

Here's how I'm integrating event information from my database with FullCalendar using PHP: Retrieve event information from the database. Organize the data into an array and customize formatting, colors, etc. Convert the array to JSON format usi ...

Revise for embedded frame contents

Is it possible to modify the HTML content of an iframe within a webpage? I currently have this code snippet: <iframe src="sample.html"></iframe> I am looking for a way to edit the contents of sample.html without directly altering the HTML co ...

Interactive form found on a webpage

Hey there! I'm currently working on a task where I want a form to be displayed when the edit button is clicked. Once the save button in the form is pressed, I want to update my database with the new information. It's crucial that this process hap ...

Using Ajax with jQuery may encounter issues when running from a local file

I have created a basic HTML file with AJAX functionality. index.html: <html> <head> <meta http-equiv="Content-Type" content="text/html; Charset=UTF-8"> <script type="text/javascript" src="jquery.js"></script> </head> ...