Retrieve the position of my dropdown menu using jQuery

Currently, I am working on creating a jQuery drop-down menu that can be used anywhere on my page in a dynamic manner. The goal is to make it flexible so that each element containing the trigger class will be positioned perfectly and trigger the drop-down when clicked. To achieve this, I need a jQuery code that will replace my drop-down with the clicked element, similar to the example shown here (positioned at the center of the clicked text): http://prntscr.com/7hw91t from the website:

Here is the HTML code I have:

<ul>
    <li class="more">
        <a href="#" class="drop-down-menu-trigger">More</a>
    </li>
    <li class="more">
        <a href="#" class="drop-down-menu-trigger">Second Menu</a>
    </li>
</ul>   

This code pertains to the elements that will open the drop-down menu when clicked: http://prntscr.com/7hwa7m. The "drop-down-menu-trigger" class triggers the opening of the drop-down menu.

Below is the drop-down menu code located at the bottom of my index.php file:

    <div id="more-drop-down-menu" class="drop-down-menu">
        <ul>
            <li>
                <a class="modal-window-trigger" name="modal-window-faq" id="faq" href="faq.php">Frequently Asked Questions</a>
            </li>
            <li>
                <a href="faq.php">Test</a>
            </li>
            <li>
                <a href="faq.php">Test</a>
            </li>
            <li>
                <a href="faq.php">Test</a>
            </li>
        </ul>
    </div>
</div>

Additionally, there is the JS code involved:

(function($)
{
    $(".drop-down-menu-trigger").click(function(e)
    {
        e.preventDefault();
        $(".drop-down-menu").css({"visibility": "visible"});
    });
})(jQuery);

Lastly, here is my CSS:

.drop-down-menu
{
    background-color: #FFFFFF;
    position: absolute;
    top: 188px;
    right: 0;
    box-shadow: 0 15px 110px rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    visibility: hidden;
}

.drop-down-menu:before
{
    right: 10px;
    bottom: 100%;
    margin-left: -15px;
    border: 15px solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-bottom-color: #FFFFFF;
}

.drop-down-menu a
{
    display: block;
    color: #000000;
    padding: 10px;
}

.drop-down-menu a:hover
{
    background-color: #F5F5F5;
}

If anyone could provide assistance with this, I would greatly appreciate it. Thank you!

Answer №1

Perhaps something along these lines, although it hasn't been tested yet. It would be beneficial for you to showcase or render your code in jsFiddle so that we can better understand what you are trying to achieve.

(function($)
{
    $(".drop-down-menu-trigger").click(function(e)
    {
         e.preventDefault();

        // Obtain the location offset using CSS
       var leftPos = $(this).offset().left,
            topPos = $(this).offset().top;

       $(".drop-down-menu").css({
           "visibility": "visible",
           "left": leftPos,
           "top": topPos
           });

    });
})(jQuery);

Revised Response:

In this updated version, I made several adjustments including CSS modifications and utilizing jQuery to ensure the caret is positioned correctly in the middle of the menu. You can view the revised code on fiddle here:

http://jsfiddle.net/screepts/rh2w16of/2/

Additionally, a screenshot showcasing the updated code functioning with your menu can be seen below.

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

"Upon completion of Uploadify, the queue will undergo a

I'm looking to personalize Uploadify by updating the queue item linked to a completed upload with information from my upload script. For example, if there's an upload error, I want the background color to change to red and display the response m ...

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

What is the equivalent of Buffer.from(<string>, 'hex') in Python?

I am currently facing the challenge of translating a Typescript library into Python. The specific library I am working with is bs58 in Typescript and its counterpart base58 in Python. My issue arises when attempting to replicate the following code: const ...

What is the best way to minimize the number of requests sent in AngularJS?

Currently in my demo, each time a user types something into an input field, a request is sent to the server. However, I would like only one request to be fired. For example, if the user types "abc," it currently fires three requests. Is there a way for the ...

JavaScript: Array methods and Functions

export function getPlanetNames(data) { const pNames = data.planets; const results = pNames.filter(function (getNames) { return getNames.name; }); return results; 'data' is stored in a separate file and consists of an object array wit ...

adjusting three sections within a flexible navigation bar

Having difficulties creating a dynamic navbar that changes on scroll and keeping the elements within the nav fixed when the menu options appear. For reference, you can check out this codepen: http://codepen.io/timothyfernandez/pen/azXQPV Any assistance w ...

Building an integrated Monaco editor using Electron and AngularJS

Struggling to integrate the Monaco editor into my Electron app. Despite following electron examples, encountering persistent errors in my application. The errors I'm facing include: "loader.js:1817 Uncaught Error: Unrecognized require call" "angula ...

Karma test encountered a provider that could not be identified

I am working with a provider called $_ConfigProvider: (function (angular) { angular.module('app') .provider('$_Config', ConfigProvider); function ConfigProvider() { .... //routes definition } ConfigProvider.prot ...

Error: The addDoc() function in FireBase was encountered with invalid data, as it included an unsupported field value of undefined during the execution

As I attempt to input data into the firebase database, an error arises: 'FireBaseError: Function addDoc() called with invalid data. Unsupported field value: undefined'. The registration form requests 2 inputs - name and email. The function handle ...

Tips for handling datetime in angular

Currently, I am working with Angular (v5) and facing an issue related to Datetime manipulation. I am trying to retrieve the current time and store it in a variable. After that, I need to subtract a specified number of hours (either 8 hours or just 1 hour) ...

Template designed in the style of Spotify with HTML5 and responsive features

I am in the process of creating a one-page website with a similar effect to that on spotify.com. Essentially, I want the background image to change as you scroll down, while still keeping elements displayed over the previous backgrounds in a smooth and res ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...

Executing a JavaScript function with jQuery

function launch() { $("p").text("Hey there", greet()); } function greet() { alert("Greetings! You have triggered another function"); } HTML: <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button onclic ...

Is there a way to attach a canvas image to an email using VB.NET?

In my project, I have successfully converted an SVG to a canvas image using canvg, then converted it to a bytearray in vb.net on the client side. I saved the image to a folder on my server in order to attach it to an email: Protected Sub Button1_Clic ...

Error: The Object #<Object> does not contain a function named 'Schema'

Below is the user model schema that we are using. However, when I try to run it on my localhost, I encounter an error: TypeError: Object # has no method 'Schema' // app/models/user.js // Required modules var neo4j = require('neo4j'); ...

What is the best way to organize data subsets in Firebase?

I am currently working on saving data from multiple sections within my webapp. One section involves storing employee information, while the other deals with employer group information. However, when I save this data in Firebase, it all gets organized by ID ...

Error: Angular is encountering an issue with accessing the property 'push' as it is currently undefined

I have successfully created a news ticker that works well in my codepen example. However, I am encountering an issue with integrating it into my code structure. The error message I am currently receiving is: Cannot read property 'push' of undefi ...

Analyzing HTML using Spark

My current project involves: Loading html sources from a csv file Developing functions to extract specific features from the html source. In the past, I used Python with BeautifulSoup for this task. However, my approach has now shifted to using Spark and ...

Encountering a parsing issue: an unexpected token was found, expecting "," instead

I'm encountering a Parsing error that states: Unexpected token, expected ",". I've been unable to pinpoint where the missing "," is located. Please refer to the image below for the exact line of the error. const cartSlice = createSlice({ name ...

Updating front end data using Node.js - A Comprehensive Guide

I am looking to create a website using node.js that can dynamically display a plot and update the data every minute without needing to refresh the entire page. As someone new to node.js, I am interested in learning how to use "get" requests to update the d ...