Stagnant updates in component's styling

I have a list box style stored in the component's data. It is bound to a listbox element. One of the styles within it is position: absolute. My goal is to position the box directly below the input element. To achieve this, I am trying to dynamically modify the listBoxStyle by fetching the top, left, and height values from the input element in the mounted hook function. However, despite my efforts, the listbox remains at its original position and doesn't move.

I am in search of a solution that allows me to move the listbox to the desired location programmatically.

Below is the code snippet:

Vue.component("employee-search", {
    props: ["small"],

    data: function () {
        return {
            searchText: "",
            isSmall: (this.small ? true : false),
            list: [],
            formControlCss: "form-control",
            fullWidthCss: "full-width",
            smCss: "input-sm",
            listBoxStyle: {
                position: "absolute",
                top: 0,
                left: 0,
                backgroundColor: "white",
                borderStyle: "solid",
                borderWidth: "1px",
                padding: "5px 25px 5px 0px",
                borderColor: "#245580"
            }
        }
    },

    template:
        '<div>' +
        '   <input ref="inputBox"' +
        '       v-model="searchText" ' +
        '       v-on:input="handleInputChange"' +
        '       v-bind:class="[formControlCss, fullWidthCss, isSmall ? smCss : \'\']" ' +
        '       placeholder="Search on name or badge #..." > ' +
        '   <div ref="listBox" v-bind:style="listBoxStyle">' +
        '   <ul v-show="list.length > 0" style="margin-top: 10px"> ' +
        '       <li ' +
        '           v-for="item in list" ' +
        '           v-on:click="handleSelect(item)" ' +
        '           style="cursor: pointer; margin-bottom: 5px;">' +
        '               {{ item.label }}' +
        '       </li>' +
        '   </ul>' +
        '   </div>' +
        '</div>',

    methods: {
        handleInputChange: function () {
            console.log("handleInputChange: " + this.searchText);
            var self = this;

            if (this.searchText.length > 2) {

                $.ajax({
                    url: "/api/badges?filter=" + this.searchText,
                    dataType: "json",
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        console.log(data);
                        self.emptyList();
                        data.forEach(function (item) {
                            self.list.push(JSON.parse(item));
                        });
                        self.positionListBox();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });

            } else {
                this.emptyList();
            }
        },

        handleSelect: function (item) {
            console.log(item);
            this.searchText = item.label;
            this.emptyList();
            this.$emit("selected", item);
        },

        emptyList: function () {
            var count = this.list.length;
            for (var x = 1; x <= count; x++) {
                this.list.shift();
            }
        },

        positionListBox: function () {

        }
    },

    mounted: function () {
        console.log("EmpSearch: ", this.$refs.listBox);
        this.listBoxStyle.top = this.$refs.inputBox.getBoundingClientRect().top + this.$refs.inputBox.getBoundingClientRect().height;
        this.listBoxStyle.left = this.$refs.inputBox.getBoundingClientRect().left;
    }
});

Answer №1

When adjusting the position of elements using properties like listBoxStyle.top and listBoxStyle.left, it is important to specify the units to avoid issues with CSS rendering.

mounted: function () {
    console.log("EmpSearch: ", this.$refs.listBox);
    this.listBoxStyle.top = this.$refs.inputBox.getBoundingClientRect().top + this.$refs.inputBox.getBoundingClientRect().height + 'px';
    this.listBoxStyle.left = this.$refs.inputBox.getBoundingClientRect().left + 'px';
}

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

Constructing a React component with a constructor

I am brand new to working with react native and I'm requesting assistance in fixing the code below. Currently, I have a view within a const and I am looking to include a constructor inside the const function. const { width } = Dimensions.get(' ...

Leveraging _.after() within an asynchronous callback, causing contamination of an array variable

I am hoping that this question is unique and not a duplicate. I tried looking for similar questions here, but couldn't find any matching results. When working with node.js, the code below seems to be causing pollution in the storage variable. I' ...

Steps for automatically playing the next song when a button is clicked

I have encountered a challenge in developing a music player. The issue lies in the loading of the next song when the user clicks the 'next' button. While the new data is successfully updated in both the state and render, the music does not automa ...

Guide to making control bar fade out when video is paused on video.js

Is there a way for the control bar to automatically disappear when the video is paused? Thank you in advance! ...

How to utilize a Jquery loop, implement a condition, and store the results in

After using dd() in PHP, the array displayed is as follows: 1 [▼0 => "1,18,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,19,20,21,22,23,24"] I need to iterate through the array and o ...

The list marquee in HTML, JS, and CSS is not being properly rendered on

I recently made changes to a code that showcases a marquee scrolling a basic HTML list. Check it out here: I am facing 3 issues that I am struggling to resolve: JS: I want the marquee to continuously show text re-entering from the right just after it ...

What is the best way to adjust the size of carousel images within a box element?

How can I ensure that carousel pictures are displayed clearly within the box without overflowing? The code I tried resulted in the pictures overflowing from the box and not being visible clearly. How can I resolve this issue? .container { width: 1490px; ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

I'd like to be able to click on the navbar and have the text color change using tailwind CSS

Click on the button to change its color. Click on another button to change its color as well, but the first button will revert back to its default color. View image description here <ul class="flex flex-col p-4 mt-4 border borde ...

Utilizing an Entity's Location for triggering an Action in AFrame

Looking to create a custom component that can track the position of a sphere within an AFrame scene and trigger an event when it reaches a specific coordinate (for example, resetting to its default position as shown below): AFRAME.registerComponent("t ...

Explore the integration of Vue.js and Laravel API for seamless and efficient web

I am struggling to implement a search function within a list of elements using Vue.js. Despite successfully displaying the list in a table, I encounter issues when attempting to filter the list based on a search term. Any assistance would be greatly appr ...

I am puzzled as to why the JSON response is visible in the browser but cannot be forwarded to the Ajax callback function, causing the page to remain on the initial request page

Currently, I am in the process of developing a web application that utilizes AJAX and servlet. My main focus right now is creating a functional login page for the application. Although the servlet successfully generates a response in JSON format, the issu ...

What is the best way to trigger UseEffect when new data is received in a material table?

I was facing an issue with calling a function in the material table (https://github.com/mbrn/material-table) when new data is received. I attempted to solve it using the following code. useEffect(() => { console.log(ref.current.state.data); ...

Choose a selection in ExtJS by finding matching attributes

Is there a convenient method to choose an item in an Ext.tree.Panel by matching it with an item based on the same attribute in an Ext.grid.Panel? For example, using something like: tree_dir.getSelectionModel().select(grid_file.getSelectionModel().getSelect ...

Having trouble getting my node.js and socket.io code to function properly

This is my code for basic broadcasting functionality on the server side: Server Side var socket = require( 'socket.io' ); var express = require( 'express' ); var http = require( 'http' ); var app = express(); var server = h ...

What is the best way to update the content within a Div element?

I'm currently working on a project in AngularJS where the data in the backend is updated every 30 seconds. I need to ensure that these changes are reflected on the front end. Is there a way to automatically refresh the div every 10 seconds to achieve ...

Function for querying database is not executing in an asynchronous manner

After setting up a function in my node server to handle querying the database and returning results, I found that using async await could help streamline the process throughout my routes. This way, I wouldn't end up with nested queries within one anot ...

Passing events from a grandchild component up to its grandparent component in VueJS 2.0

Vue.js 2.0 appears to have a limitation where events cannot be emitted directly from a grand child component to its grand parent. Vue.component('parent', { template: '<div>I am the parent - {{ action }} <child @eventtriggered="pe ...

Having trouble getting Django to display images using jQuery? Uncaught Reference Error may be preventing it

Currently, I am experimenting with implementing a jquery example on my django-based website. As I am still in the learning phase, I kindly ask for your patience. This is a snippet of what my code looks like at this point: {% extends "base.html" %} {% loa ...