Jquery Position behaving unexpectedly during initial invocation

My goal is to have the autocomplete menu open above the input box if there is not enough space below it. The code functions properly, except for the initial render. It consistently displays at the bottom in the following scenarios: 1. When starting a search 2. When clicking in the field and triggering a search for the existing text in the field

Even though the position.my and position.at contents are correctly set for "above" placement, the menu still appears below the input box.

I have a resize function that is bound to window scroll and resize events. When scrolling the page, the menu is positioned correctly. I suspect that the positioning happens before the full rendering.

Code

_renderMenu function hook

// Autocomplete _renderMenu function
$(autocomplete_object)._renderMenu = function( ul, item ) {
      var that = this;
      jQuery.each( items, function( index, item ) {
        that._renderItemData( ul, item );
      });

      // Make sure the menu is now shown to calculate heights and etc (menu is now rendered, position rendering next)
      jQuery(ul).show();

      autocomplete.resize(ul, options);
      autocomplete.create_dropdown_handlers(ul, options);
}

Resize Function

// Resize function
function resize( ul, options ) {
  var height;

  // If the height of the results is smaller than the space available, set the height to the results height
  var ul_height = 0;
  jQuery(ul).find('li').each(function(i, element){
      ul_height += jQuery(element).height();
  });


  // Make the height the full height available below the input box but above the window cut off
  // Move the dropdown above the input box if there is not enough room below the input box
  var $parent = jQuery("#" + options.name);
  var padding = 25; // arbitrary number to prevent dropdown from hitting the window border in either direction
  var bottom_distance = autocomplete.getViewportHeight() - ($parent.offset().top + $parent.height()) - padding;

  var bottom_limit = 200;

  var ul_position = { 
                      my: "left top",
                      at : "left bottom",
                      of: $parent,
                      collision: 'none' 
                    };

  height = bottom_distance;

  if (bottom_distance < bottom_limit) {
    var top_distance = $parent.offset().top - padding;
    height = top_distance;
    // ----- It is getting here fine! -----
    ul_position.my = "left bottom";
    ul_position.at = "left top";
  }


  // We have room to show the entire dropdown results without a scrollbar
  if (ul_height < height) {
    height = 'auto';
  }

  // Position below or above parent depending on space
  jQuery(ul).position(ul_position);

  jQuery(ul).css({height: height == 'auto' ? height : height + 'px'});
 }

TLDR:

Jquery position is set to show above input field, but it still shows below?

Answer №1

After encountering an issue with the positioning of the autocomplete object, I realized that I needed to update both the position value of the autocomplete object and the ul position. It seemed that the initial render was inheriting the autocomplete's default position value (which is set to display below the input box).

Here is the updated line of code:

// Make this change in the resize function after jQuery(ul).position(ul_position);
$parent.autocomplete("option", "position", ul_position); // This fixed the rendering issue!

Added to the resize function

function resize (ul, options) {
    ... 
    calculate the necessary height and position
    ...

    jQuery(ul).position(ul_position);
    $parent.autocomplete("option", "position", ul_position); // <-- Added to ensure correct rendering based on position

}

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

The HTML video controls in Safari take precedence over the window.name attribute

When using Safari 8.0.5, the controls attribute for the video element will change the value of window.name to "webkitendfullscreen". This is significant because I rely on using window.name to store client-side data in Safari's private mode, where loca ...

The JSON response may be null, yet the data flows seamlessly to the success function in

Currently, I am facing an issue with Ajax. The situation is as follows: I want to check if a user is available by typing their email address. Therefore, I have created a JavaScript function that includes an Ajax script for this purpose. Here is my code: $ ...

Error: Invalid Argument - The argument 'PanelController' is expected to be a function, but it is undefined

Here is a snippet of my HTML code: <body ng-controller="StoreController as store"> ........... <section ng-controller="PanelController as panel"> <ul class="nav nav-pills""> <li ng-class="{active:panel.isSe ...

Is there a way for me to remove an uploaded image from the system

Here is an example of my HTML code: <input type='file' multiple/> <?php for($i=0;$i<5; $i++) { ?> <div class="img-container" id="box<?php echo $i ?>"> <button style="display: none;" type="submit" cl ...

The key to subscribing only once to an element from AsyncSubject in the consumer pattern

When working with rxjs5, I encountered a situation where I needed to subscribe to an AsyncSubject multiple times, but only one subscriber should be able to receive the next() event. Any additional subscribers (if still active) should automatically receive ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

Encountering an error message of "Cannot POST" while trying to send data through a REST client application

Upon my attempt to add a new entry into the Doctors database I created, I encountered an error that has left me perplexed. This is how my server.js file appears: const express = require('express'); const bodyParser = require('body-parser&a ...

Enhancing a specific element in a view using Node.js alongside Express and EJS

My goal is to modify value2 on the server side and update the view accordingly. The question at hand is: How can I efficiently refresh the view with only the new value2? Server: var express = require("express"); var app = express(); app.set('view ...

Bringing in data using .json files in a react native environment with Redux

I have developed a fitness app and I am utilizing Redux to store all the sets and workouts. Currently, I have manually entered all the exercises into Redux data for testing purposes. However, I now have all the exercises stored in a .json file and I want t ...

Mobile Bootstrap4 NavBar Bug Fix

I am currently working on coding a website with Bootstrap. The navbar functions perfectly on desktop, but when accessed via mobile device, the button containing all the links does not work. Here is a picture for a more accurate description Below is my HTM ...

Comparing Arrays with jQuery

I am currently working on a tic-tac-toe project that involves a simple 3x3 grid. I have been storing the index of each selected box in an array for each player. However, I am facing difficulty in comparing my player arrays with the winner array to determin ...

What is the best way to have text fit perfectly into a table cell?

In my asp.net table, the first column contains captions for each row of data. The length of these captions varies, with different amounts of words in each one. I am looking to align the first letters of each caption at the beginning edge of the cells (left ...

Tips for maintaining the fixed size of a table header and preventing it from resizing in width

My goal was to create a table using divs with fixed headers while scrolling vertically. However, I encountered an issue where the header width seemed to shrink and became misaligned with the rows. Even setting the width to 100% did not resolve this probl ...

The image placeholder is missing

This is my custom Results component: This is my custom Thumbnail component: `import React from "react"; const Thumbnail = ({ result }) => { return ( <div> <h1>Thumbnail</h1> </div> ); }; export default Thumb ...

What could be causing the absence of a background image in CSS?

When I try to view my local desktop file, the CSS background image isn't showing up. Here's the code I'm using: <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" text="type/css" href="dis ...

What is the best way to use jQuery to only display the form that is checked among the 3 forms shown by checkboxes?

Currently, I am working on creating a feed feature where users can post links, text, or images. Each type of posting has its own form for simplicity. At the moment, I have managed to display each form with a checkbox, but I am struggling to find a way to ...

We are creating a table in JavaScript and mistakenly adding an unnecessary tbody

I am currently utilizing a combination of plain JavaScript and Jquery in order to dynamically generate a table. The issue arises when I attempt to use a for loop to iterate through the data obtained from an Ajax request, as it fails to create new rows. To ...

I am unable to connect my jQuery

I've searched far and wide on numerous coding forums for solutions to this issue. It's usually just minor syntax mistakes like forgetting a closing tag or improper src attribute formatting. Despite double-checking, my html and js seem to be erro ...

Lambda script for Amazon Alexa Skill is not functioning as expected

I am currently developing a Lambda function for an Amazon Alexa skill using NodeJS. For those unfamiliar, Alexa is a cylindrical speaker that responds to voice commands, and a "skill" is essentially a voice-operated app for the device. This particular func ...