jQuery UI Position Function

A complete guide to precise element placement, collision detection, and practical positioning patterns for modern web interfaces.

Understanding the jQuery UI Position Function

The jQuery UI Position function stands as one of the most powerful and flexible utilities for web developers seeking to precisely position elements relative to other elements, the viewport, or even the mouse cursor. Unlike traditional CSS positioning which often requires complex calculations and manual adjustments, the Position function provides a declarative API that handles the mathematics of element placement automatically. This capability becomes essential when building modern web interfaces that require dynamic, responsive positioning behavior. From dropdown menus attached to buttons to tooltips displaying contextual information, the Position function provides the foundation for countless interface patterns.

The Position utility was introduced in jQuery UI 1.8 and has since become a cornerstone of jQuery UI's utility collection. What makes this function particularly valuable is its ability to work independently of the jQuery UI widget ecosystem--it can be used in any project that includes jQuery, making it accessible to developers who may only need this specific functionality. The function addresses a fundamental challenge in web development: creating interfaces where elements need to be positioned relative to other elements without being affected by the document's offset parent chain.

Understanding the Position function also provides insight into how jQuery UI approaches complex interface challenges. The same utility powers the positioning behavior of jQuery UI widgets like Tooltip, Dialog, and Autocomplete, meaning mastery of this function directly translates to better understanding of those widgets' configuration options.

What You'll Learn

In this comprehensive guide, we'll cover the fundamental concepts and positioning terminology, then dive deep into the essential parameters that control element alignment. You'll discover how collision detection automatically handles viewport boundaries, ensuring positioned elements remain visible even near edges. We'll explore advanced options including the using callback for custom positioning logic and the within parameter for constraining elements to specific containers. Through practical code examples for tooltips, dropdown menus, modal dialogs, and context menus, you'll gain hands experience with real-world applications. Finally, we'll cover common pitfalls to avoid and best practices that ensure performant, maintainable positioning in your projects.

  • Core concepts and positioning fundamentals
  • Essential parameters (my, at, of)
  • Collision detection and handling strategies
  • Advanced options including using callback and within
  • Practical use cases with code examples
  • Common pitfalls and best practices
  • Browser compatibility considerations

Style: Professional, confident, tutorial-focused

Core Concepts and Fundamentals

The jQuery UI Position function fundamentally changes how developers think about element placement by introducing a relative positioning model that abstracts away the complexity of offset calculations. At its core, the function allows you to position one element (the "positioned" element) relative to another element (the "target" element), with precise control over which edges or points of each element are aligned. This is achieved through a combination of parameters that specify the anchor points on both elements and the behavior when positioning would cause the element to overflow its container.

Key Characteristics

The key characteristics that make the Position function indispensable for modern web development include its declarative API that lets you specify the desired position rather than calculating coordinates manually, an anchor point system that provides granular control over which edges and points align between elements, automatic collision detection that handles viewport boundaries without additional code, and its availability as an independent utility that works without requiring the full jQuery UI widget stack. These characteristics combine to create a positioning solution that is both powerful and approachable.

Positioned Element vs Target Element

Understanding the distinction between the positioned element and the target element is crucial. When you call the position method on a jQuery selection, that selection represents the element that will be moved. The position configuration then specifies where that element should end up in relation to another element or coordinate. This separation of concerns makes the API intuitive: you select the element you want to move, then tell it where to move relative to. As noted in the jQuery UI API documentation, the function sets the top and left CSS properties of the positioned element based on the configuration provided.

CSS Requirements

The Position function works exclusively with absolutely positioned elements. The function sets the top and left CSS properties, meaning the element must have position: absolute (or position: fixed in some cases) for positioning to take effect. This requirement makes sense when you consider the use cases: tooltips, dropdown menus, modal overlays, and similar interface elements all share the characteristic of being positioned independently from the normal document flow. The function does not modify the element's positioning type--it assumes the element is already absolutely positioned and simply calculates and applies the coordinates.

// Ensure element is properly configured before positioning
$(".tooltip").css("position", "absolute").position({
 my: "top center",
 at: "bottom center",
 of: ".has-tooltip",
 collision: "flipfit"
});

Related Resources:

Essential Parameters: my and at

The my and at parameters form the foundation of the Position function's configuration, together defining which point on the positioned element aligns with which point on the target element. These parameters accept string values that specify horizontal and vertical alignment, with optional pixel or percentage offsets. Understanding these parameters thoroughly is essential because they control the fundamental relationship between the two elements being positioned.

The my Parameter

The my parameter specifies the anchor point on the element being positioned. The default value is "center", which means the center of the positioned element will be aligned with whatever point is specified on the target. The parameter accepts horizontal values of left, center, or right, combined with vertical values of top, center, or bottom. These can be written in either order, so "left top" and "top left" are equivalent. The CSS convention of horizontal-first ordering (like background-position) is followed, where a single value like "right" is automatically expanded to "right center".

The at Parameter

The at parameter works identically but specifies the anchor point on the target element--the element or location that the positioned element is aligned against. By default, at is also "center", meaning the positioned element's anchor point (specified by my) will align with the center of the target element. The same horizontal and vertical values are accepted, and the same single-value expansion rules apply.

Common Alignment Patterns

The following table shows how different my and at combinations create predictable alignment patterns that remain consistent regardless of where the target element is in the document:

my Valueat ValueResult
"left top""left top"Top-left corners align
"center""center"Elements center on each other
"left top""left bottom"Position below target
"bottom center""top center"Position above target
"right top""left top"Position to right of target
"right bottom""left bottom"Position below and to the right
"center top""center bottom"Center aligns with bottom of target

Using Offsets with my and at

Beyond simple alignment, both my and at support offset values that provide fine-grained control over the final position. Offsets can be specified in pixels (using a number) or as a percentage of the positioned element's or target element's dimensions, respectively. The offset follows the horizontal or vertical keyword and can be positive or negative.

Examples:

  • "left+10 top-5" -- 10px right, 5px above anchor point
  • "right+10%" -- 10% of target width to the right of right edge
  • "bottom+25%" -- 25% of target height below the bottom edge

Percentage offsets are particularly useful for responsive designs because they scale proportionally with the elements they reference. An offset of "bottom+25%" moves the positioned element down by a quarter of the target element's height, ensuring the relative positioning remains consistent as elements resize. As demonstrated on the jQuery UI Position demo page, this approach works seamlessly with draggable elements to show positioning in action.

Practical Configuration Examples:

// Position tooltip above trigger with 10px gap
$(".tooltip").position({
 my: "bottom center",
 at: "top center+10",
 of: ".has-tooltip"
});

// Position dropdown below trigger with left edges aligned
$(".dropdown").position({
 my: "left top",
 at: "left bottom",
 of: ".dropdown-trigger"
});

// Position sidebar to the right of container
$(".sidebar").position({
 my: "left top",
 at: "right top",
 of: ".main-content"
});

The of Parameter: Defining the Target

The of parameter specifies the element, selector, or coordinate that serves as the positioning target. This parameter is what makes the Position function truly versatile, as it allows positioning against virtually any reference point in the document. Understanding the different types of values that of accepts and when to use each is crucial for leveraging the full power of this functionality.

Supported Target Types

Selector String:

$("#tooltip").position({
 of: "#button"
});

DOM Element:

$("#tooltip").position({
 of: document.getElementById('button')
});

jQuery Object:

$("#tooltip").position({
 of: $(".trigger").first()
});

Mouse Events:

$(document).on('mousemove', function(event) {
 $("#tooltip").position({
 of: event,
 my: "left+5 top+5",
 collision: "fit"
 });
});

Default Behavior

When of is not specified or is set to null, the Position function defaults to positioning relative to the viewport window. This is useful for modal dialogs or overlay elements that should always appear centered on the screen, regardless of where they appear in the document. The viewport-based positioning is also what enables the collision detection to work with the browser window boundaries, ensuring positioned elements never extend beyond what the user can see.

Important Considerations

There are several important considerations to keep in mind when working with the of parameter. First, the Position function does not support positioning against hidden elements--attempting to position relative to a hidden target will not produce meaningful results because hidden elements have no calculated dimensions or position in the layout. Second, the function tracks the target element's position, meaning if the target moves due to window resizing, scrolling, or DOM changes, you can simply call the position function again to update the positioned element's location. Third, event-based positioning using of: event enables cursor-following effects that are particularly useful for custom tooltips and context menus.

When combining mouse event positioning with collision detection, the system ensures the positioned element remains visible within the viewport even when the cursor is near edges. This behavior is essential for creating usable context menus and interactive elements that follow the user input.

Related Resources:

Collision Detection and Handling

Collision detection represents one of the most valuable features of the jQuery UI Position function, solving a practical problem that arises whenever elements are positioned near viewport edges. When a positioned element would extend beyond the boundaries of its container (by default, the browser window), collision detection automatically adjusts the position to keep as much of the element visible as possible. This behavior is essential for creating usable interfaces that work consistently across different screen sizes and viewport configurations.

Collision Strategies

flip (default): Attempts the specified position, then if overflow occurs, tries the opposite position by flipping across the target's anchor point.

fit: Shifts the positioned element away from the overflowing edge rather than flipping to the opposite side.

flipfit: Combines both approaches--first flips to find the side with more space, then applies fit logic for maximum visibility.

none: Disables collision detection entirely.

How Collision Detection Works

The collision algorithm follows a systematic process to ensure positioned elements remain visible within container boundaries. First, the algorithm calculates the initial position based on the my, at, and of parameters, determining where the element would be placed without any collision handling. Next, it checks if the positioned element extends beyond the container boundaries in either the horizontal or vertical dimension. If overflow is detected, the specified collision strategy is applied: flip attempts to use the opposite position, fit shifts the element away from the overflowing edge, and flipfit combines both approaches. The algorithm then recalculates the position with the collision adjustments applied and finally sets the element's top and left CSS properties to the final calculated position.

Configuration Examples

// Default collision behavior (flip)
$(".tooltip").position({
 my: "top center",
 at: "bottom center",
 of: ".trigger",
 collision: "flip" // Default behavior
});

// Independent horizontal/vertical collision handling
$(".tooltip").position({
 my: "left top",
 at: "right top",
 of: ".trigger",
 collision: "flip fit" // Horizontal flip, vertical fit
});

// Maximum visibility with flipfit
$(".dropdown").position({
 my: "left top",
 at: "left bottom",
 of: ".dropdown-trigger",
 collision: "flipfit"
});

// Disable collision detection when needed
$(".custom-overlay").position({
 my: "center center",
 at: "center center",
 of: window,
 collision: "none"
});

The flip strategy doesn't simply mirror the position--it re-evaluates the entire position configuration to find the best fit. After flipping, collision detection runs again, potentially finding that the flipped position fits perfectly or may need further adjustment. The fit strategy is particularly valuable for centered modal dialogs that might extend beyond the viewport on smaller screens, as it shifts the dialog to remain fully visible while maintaining its centered position as much as possible.

Related Resources:

The using Callback Function

The using parameter provides a powerful extension point for the Position function, allowing custom handling of the calculated position coordinates. Instead of (or in addition to) having the function directly apply the position to the element, you receive the calculated top and left values in a callback function where you can apply them using any method you choose. This opens up possibilities for animations, CSS custom properties, or integration with other JavaScript libraries.

Callback Signature

using: function(position, feedback) {
 // position: { top: number, left: number }
 // feedback: { element, target, horizontal, vertical, important, ... }
}

// The 'this' context refers to the positioned element

Practical Example: Animated Positioning

$("#tooltip").position({
 my: "left top",
 at: "right bottom",
 of: "#trigger",
 collision: "flipfit",
 using: function(position, feedback) {
 // Apply position with animation for smooth movement
 $(this).stop().animate({
 top: position.top,
 left: position.left
 }, 200);

 // Log collision information for debugging
 console.log("Horizontal:", feedback.horizontal);
 console.log("Vertical:", feedback.vertical);
 }
});

Feedback Object Properties

The feedback object passed to the callback provides comprehensive information about the positioning calculations and any collision handling that occurred. The element property provides a reference to the positioned element along with its dimensions, enabling size-aware adjustments. The target property offers a reference to the target element with its dimensions and position. The horizontal and vertical properties indicate the direction of any collision detected, such as 'fit' or 'flip', helping you understand how the position was adjusted. The important property shows which dimension took precedence in resolving collisions, revealing which axis was prioritized when both horizontal and vertical collisions occurred.

Advanced Callback Patterns

Beyond simple animation, the using callback enables several advanced patterns for sophisticated positioning behaviors. Using CSS custom properties for hardware-accelerated positioning separates the positioning logic from styling, making it easier to create consistent positioning across multiple elements or implement theme-based adjustments. Conditional styling based on collision detection allows you to apply different visual treatments depending on whether collision occurred, such as adding a visual indicator when the element had to flip positions. Coordinating multiple element positions enables related elements to maintain consistent relative placement through the callback's reference to this. Integration with animation libraries like GSAP creates smooth, professional transitions for positioned elements.

// CSS custom properties pattern
using: function(position) {
 this.style.setProperty('--pos-top', position.top + 'px');
 this.style.setProperty('--pos-left', position.left + 'px');
}

// Conditional styling based on collision
using: function(position, feedback) {
 $(this).css({
 top: position.top,
 left: position.left
 }).toggleClass('flipped', feedback.horizontal === 'flip');
}

The within Parameter and Container Boundaries

The within parameter specifies the container that bounds the collision detection, allowing positioned elements to be constrained within a specific region of the page rather than the entire viewport. By default, collision detection uses the browser window as the boundary, but many interface designs require elements to remain within a particular container, such as a modal dialog's content area or a scrollable panel.

Default Behavior

By default, collision detection uses the browser window as the boundary. Elements will flip or fit to remain visible within the viewport. This behavior is appropriate for most full-page interfaces but can cause issues when positioned elements should remain within specific containers.

Constraining to a Container

$(".dropdown-menu").position({
 my: "left top",
 at: "left bottom",
 of: ".dropdown-trigger",
 within: ".scrollable-container",
 collision: "flipfit"
});

When to Use within

There are several scenarios where the within parameter becomes essential for creating proper user interfaces. For scrollable containers, keeping dropdowns within scrollable areas prevents them from floating above their intended region when users scroll the container. For modal dialogs, constraining tooltips and validation messages to the modal content area maintains the modal's visual integrity and ensures all related content remains connected. For card components, keeping positioned elements within card boundaries creates self-contained UI units that don't break out of their containers. For dashboard layouts, maintaining positioning within grid containers ensures elements adapt as the dashboard reflows across different viewport sizes.

When within is specified with a selector, jQuery uses the first matching element as the collision boundary. The Position function then calculates whether the positioned element would extend beyond this container's boundaries and applies collision detection accordingly. It's important to note that the container must have position: relative, position: absolute, or position: fixed for the boundary calculations to work correctly, because boundary detection relies on the container's position in the document.

Related Resources:

Practical Use Cases and Examples

Tooltip Positioning

Tooltips represent one of the most common applications, where informational elements need to appear near their associated trigger elements. Tooltips typically position above or below the trigger, with options for left, center, or right alignment depending on available space. The collision detection ensures tooltips remain visible even when triggers are near viewport edges, automatically flipping to the opposite side if needed.

$(".tooltip").position({
 my: "top center",
 at: "bottom center",
 of: ".has-tooltip",
 collision: "flipfit"
});

Dropdown Menu Positioning

$(".dropdown-menu").position({
 my: "left top",
 at: "left bottom",
 of: ".dropdown-trigger",
 collision: "flipfit",
 within: ".nav-container"
});

Modal Dialog Centering

Modal dialogs often need to be centered within the viewport or within a specific container. The default positioning (my: "center", at: "center") with no of parameter achieves viewport centering without additional configuration. For dialogs that should center within a specific container rather than the viewport, provide the container selector to the of parameter.

$("#custom-dialog").position({
 my: "center center",
 at: "center center",
 of: window,
 collision: "fit",
 using: function(position) {
 $(this).css({
 top: position.top,
 left: position.left
 });
 }
}).show();

Context Menu Positioning

Context menus that appear on right-click represent an excellent application of the Position function. By positioning relative to mouse events (using of: event in a contextmenu event handler), the menu appears exactly where the user clicked.

$(document).on('contextmenu', function(event) {
 event.preventDefault();
 $("#context-menu").position({
 my: "left top",
 at: "left top",
 of: event,
 collision: "flipfit"
 }).show();
});

Custom Select Menu

Custom select menus can use the Position function to position a custom dropdown relative to the native or custom trigger element. This enables styling flexibility while maintaining predictable positioning behavior.

$(".custom-select-dropdown").position({
 my: "left top",
 at: "left bottom",
 of: ".custom-select-trigger",
 collision: "flipfit",
 within: ".form-container",
 using: function(position) {
 $(this).stop(true).fadeIn(150).css({
 top: position.top,
 left: position.left
 });
 }
});

Related Resources:

Best Practices and Common Pitfalls

Common Pitfalls to Avoid

Positioning Hidden Elements: The Position function requires both the positioned element and the target element to be visible in order to calculate their dimensions and positions. If you need to show a positioned element, call the position method after the element is visible, or ensure the target element is visible during positioning.

Wrong Positioning Type: Ensure positioned elements have position: absolute or position: fixed before calling the position function. The function sets top and left properties, which only affect absolutely or fixed positioned elements.

Ignoring Dynamic Changes: The Position function doesn't automatically track changes after the initial call. Re-position elements when content or layout changes, such as after dynamic content loads or window resizing occurs.

Performance Optimization

For interfaces with many positioned elements or frequent position updates, performance becomes a critical consideration. The Position function performs layout calculations that can trigger browser reflows, so calling it rapidly (such as in a scroll or mousemove handler) should be done carefully. Implement debouncing for position updates in event handlers to reduce the number of calculations during rapid events. Use CSS transforms (transform: translate()) for animated positioning instead of animating top and left directly, as transforms are hardware-accelerated by browsers. Be aware that the within parameter impacts performance because collision detection must check boundaries against a specific container--when within references a complex container with many descendant elements, the collision calculations become more expensive. Clean up references when removing positioned elements from the DOM to prevent memory leaks from lingering event handlers and closures.

Responsive Considerations

For responsive designs, adjust positioning configuration based on viewport size to ensure positioned elements work well across all screen dimensions:

function getPositionConfig() {
 if (window.innerWidth < 768) {
 return {
 my: "left center",
 at: "right center",
 collision: "flipfit"
 };
 }
 return {
 my: "left top",
 at: "left bottom",
 collision: "flipfit"
 };
}

$(".tooltip").position(getPositionConfig());

Internationalization can affect positioning when translated content changes element sizes. Text in different languages often has different lengths, so a tooltip positioned perfectly for English might not fit for German or Chinese content. Consider using the using callback to validate positioning after content loads and adjust if needed.

Debugging Tips

When positioned elements don't behave as expected, use these strategies to identify and resolve issues quickly. Use the using callback to log position calculations and inspect the calculated coordinates--compare these against your expected values to identify calculation errors. Check element visibility before positioning, as hidden elements have no dimensions for the function to work with. Verify CSS positioning rules are applied using browser developer tools to confirm the element has the correct position value. Test across different viewport sizes to catch responsive issues that might only occur at certain screen dimensions. The jQuery UI Position demo provides an interactive playground where you can experiment with different configurations to understand how they affect positioning behavior.

// Debugging with using callback
using: function(position, feedback) {
 console.log('Calculated position:', position);
 console.log('Collision feedback:', feedback);
 $(this).css({
 top: position.top,
 left: position.left
 });
}

Frequently Asked Questions

What is the difference between jQuery's .position() and jQuery UI's .position()?

jQuery core's .position() is read-only--it returns the current position relative to the offset parent. jQuery UI's .position() with options actually moves the element to a new position. jQuery UI extends the core method with additional configuration options like my, at, collision, and using.

How do I reposition elements when the window resizes?

Call the position function again in a resize event handler. Consider debouncing the handler for performance. You can also use ResizeObserver to detect size changes in specific elements and trigger repositioning only when needed.

Can I use the Position function with fixed positioning?

Yes, but collision detection will use the viewport boundaries. The Position function sets top/left values, which work with position: fixed. However, the 'within' parameter may not behave as expected since fixed elements are positioned relative to the viewport.

How do I position multiple elements relative to one target?

Call position() on each element with appropriate my/at configurations. For coordinated positioning, use the 'using' callback to apply similar positioning logic to multiple elements simultaneously.

Why isn't my element positioning correctly?

Common causes include: element is hidden (visibility: hidden or display: none), missing position: absolute/fixed, target element is also hidden, or z-index issues. Check the browser console for errors and verify CSS positioning in developer tools.

How does collision detection work with percentage offsets?

Percentage offsets are calculated relative to the element they modify--my offsets use the positioned element's dimensions, at offsets use the target element's dimensions. Collision detection runs after offsets are applied.

Conclusion

The jQuery UI Position function provides a robust, well-tested solution for element positioning that addresses the complex challenges of creating modern web interfaces. Its declarative API abstracts away the mathematics of coordinate calculation while providing powerful features like collision detection, flexible target specification, and extensible callbacks. From simple tooltip implementations to sophisticated multi-element positioning systems, the function adapts to a wide range of requirements.

Key Takeaways

Mastering the core parameters--my, at, and of--provides the foundation for effective positioning in any web interface. The my and at parameters control the precise alignment between elements, allowing you to specify which edges or points connect, while of specifies the target element or coordinate. Collision detection through the collision parameter ensures positioned elements remain visible across different viewport sizes and positions, automatically adjusting to prevent overflow using flip, fit, or flipfit strategies. The using callback enables custom handling for animations and integration with other systems, and the within parameter constrains positioning within specific containers for contained interfaces.

Next Steps

Continue practicing with the interactive demo at jqueryui.com/position to build intuition for how different parameter combinations affect positioning behavior. Explore how the Position function integrates with jQuery UI widgets like Tooltip, Dialog, and Autocomplete to understand how these widgets leverage the same positioning logic. Apply these positioning patterns to your own projects, starting with simple tooltips and progressing to more complex multi-element positioning systems. Consider the performance implications in complex interfaces and implement debouncing and efficient cleanup strategies for maintainable code.

The Position function's integration with jQuery UI widgets and its standalone availability make it an accessible tool for any project using jQuery. Whether building dropdown menus, tooltips, modal dialogs, or custom positioning behaviors, the jQuery UI Position function provides the flexibility and reliability needed for professional web development.

Continue Learning:

Ready to Build Dynamic Web Interfaces?

Our team specializes in creating responsive, user-friendly web applications with modern JavaScript techniques.

Sources

  1. jQuery UI Position API Documentation - Comprehensive API reference with syntax, options, and code examples
  2. jQuery UI Position Demo - Working examples showing position functionality with draggable elements
  3. jQuery UI Tooltip Documentation - Shows how position integrates with widgets
  4. GeeksforGeeks jQuery UI Position Method - Tutorial-style explanation