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

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

Struggling with z-index or float issues on Chrome and Safari with CSS styling

Check out my website at I have incorporated the Easy Slider 1.7 plugin from this source and made some custom JavaScript modifications for a banner rotator. The issue I am facing is that on webkit browsers, the navigation links (1,2,3,4,5) on the banner a ...

Stop users from skipping ahead in an HTML5 video

Struggling to stop a user from seeking on the video player. I've attempted to bind to the event, but it's not working as expected. Any suggestions on how to successfully prevent this action? @$('#video').bind("seeking", (e) =& ...

The background suddenly vanishes once the background-image property is set to no-repeat

I'm currently attempting to add a background image to my WordPress website. .content:before { content: ""; background-image: url("gfx/SevenWonders.jpg"); /*background: #fff;*/ background-size:600px 700px; background-repeat: no-repeat; position: absol ...

Using JavaScript, concatenate text from each line using a specified delimiter, then add this new text to an unordered list element

I am looking to extract text from named spans in an unordered list, combine them with a '|' separating each word within the same line, and append them to another ul. Although my code successfully joins all the words together, I'm struggling ...

Is there a way to have an image expand to fit the entire screen before scrolling to view another image?

I'm working on a website and I want to have an image that automatically adjusts to fit any screen size. Users should be able to scroll down to see more content or another image. A similar effect can be seen on this site: . Any suggestions would be rea ...

Retrieve the Id value from a Kendo Hierarchical grid

I have a hierarchical grid set up with a ClientDetailTemplate in the following manner. @(Html.Kendo().Grid(Model.NotesList) //Binding the grid to NotesList .Name("activityNotesGrid") .Columns(columns => { // Creating a col ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

How to Use jQuery to Detect Audio Position in HTML

Is it possible to use the HTML5 Audio tag with an eventListener or action using Dom/jQuery to trigger an event during playback or at the end? This answer mentions currentTime but lacks examples. Pseudo code provided below. <!DOCTYPE html> <html& ...

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

When the resolution changes, the text shifts away from the bar in CSS

When I adjust the resolution of my display, the text on my top bar also changes. Can anyone help me fix this issue? In normal view: With changed resolution or smaller browser window: This is my HTML code: <body> <div class="top-panel"> ...

Show side by side using javascript

My dilemma lies in having a set of cards that are meant to be displayed inline, but I have to initially hide them using "display: none". When a specific button is clicked, I aim to reveal these cards; however, upon doing so, each card seems to occupy its o ...

Email responses containing unidentifiable values

Currently, I am working on implementing AJAX for my contact form to send form data to the server. The objective is to have the server email me the user's information extracted from the input fields. However, I'm encountering an issue where the f ...

Steps for deactivating the click event triggered by Bootstrap Collapse API

Currently, I am incorporating Twitter's Bootstrap 'Collapse' plugin in a project. However, I found the functionality of having to click on each parent element to toggle collapsible items quite inconvenient. To address this, I decided to crea ...

Has $.support.fixedPosition feature been removed starting from version 1.8?

While browsing the jQuery changelog, I noticed that the $.support.fixedPosition feature introduced in version 1.7 seems to have disappeared in version 1.8. Can anyone shed some light on where it has been relocated or if it has been removed altogether? ...

Begin by executing the initial commit task with Git through Gulp, followed by performing the

I am currently working on a project and I am trying to use gulp to commit and push to git. However, I am encountering an issue where the push task is not waiting for the commit task to complete before running... Can anyone assist me with this? I want to s ...

Avoid using the JavaScript 'Sys.WebForms..' function if there is no ScriptManager present on the page

Currently, I am using a single JavaScript binding in the Master Page for my entire project. However, the Master Page does not include a ScriptManager. This means that some pages have Ajax components, such as UpdatePanel, while others do not. The 'Sys. ...

Create a custom Android home screen widget using JavaScript or another programming language

I have a project in mind to create an Android App and include a home-screen widget. While I know it can be done with Native Android, my preference is to use JavaScript for development. Would anyone happen to know of any other solutions that allow the use ...

Tips for automating the execution of Chrome extension code on pages with infinite scrolling

Creating my debut Chrome extension, I'm developing a tool to substitute text on web pages. The current code effectively operates on content loaded by DOMContentLoaded. However, when pages employ infinite scrolling and new content is added, the text r ...

The triggering of routing in Next.js is not established by useEffect

I'm facing an issue with my Next.js dynamic page that uses routing based on steps in the state. The route is supposed to change whenever a step value changes, like from null to "next" or back. However, the useEffect hook doesn't seem to be reacti ...