Submenu not appearing in context menu

Check out this demo I created with a canvas menu. When you click on the canvas, a menu appears. Hover over the "Aggregate" option to reveal a second submenu on the right.

The issue arises when you mouse out of "Aggregate" and then hover back in – the position of the submenu shifts. Can you spot the error in the code?

Here is the HTML:

<div id="canvas" style="width:400px;height:400px;background-color:#ff33ff;"></div>

    <div id="menu1" class="context-menu">
      <ul>
        <li>
          <a href="javascript:void(0);">Display</a>
        </li>
        <li id="li1">
          <a href="javascript:void(0);">Aggregate</a>
        </li>
        <li id="li2">
          <a href="javascript:void(0);">Order by</a>
        </li>
        <li>
          <a href="javascript:void(0);">Group by</a>
        </li>
      </ul>
    </div>

    <div id="menu2" class="context-menu">
      <ul>
        <li>
          <a href="javascript:void(0);">Count</a>
        </li>
        <li>
          <a href="javascript:void(0);">Sum</a>
        </li>
        <li>
          <a href="javascript:void(0);">Average</a>
        </li>
      </ul>
    </div>

And here's the JavaScript:

$('#canvas').click(function(e) {

    var top = e.pageY;
    var left = e.pageX;

    $("#menu1").show();
    $("#menu1").offset({ top: top, left: left });

    $('#li1').mouseenter(function() {
          $("#menu2").offset({ top: top+20, left: left+120 });
            $("#menu2").show();
    });

    $('#li1').mouseleave(function() {
        $("#menu2").hide();
    });

    $('#menu2').mouseenter(function() {
            $("#menu2").show();
    });

    $('#menu2').mouseleave(function() {
            $("#menu2").hide();
    });

});

Lastly, the CSS:

.context-menu {
  border:1px solid rgba(0,0,0,.15);
  background-color:#ffffff;
  padding:6px 0 0 0;
  display:none;
}
.context-menu ul {
  padding:0;
  list-style:none;
}
.context-menu li {
  background-color:#ffffff;
}
.context-menu li:hover {
  background-color:rgb(248,248,248);
}
.context-menu a {
  color:#333;
  text-decoration: none;
  line-height:24px;
  margin-left:20px;
}
#menu1{
  position:absolute;
  width:140px;
}
#menu2{
  position:absolute;
  width:100px;
}

Answer №1

Instead of using offset, try utilizing css instead.

It appears that each time offset is invoked within mouseenter, it increments the current position of the menu.

By employing the css method, you can effectively establish fixed top and left positions rather than continually adjusting the current location.

Answer №2

For optimal efficiency, move this code snippet

$("#menu2").offset({ top: top+20, left: left+120 });
outside of the mouseenter function. This will prevent it from being executed each time the mouse enters.

$('#li1').mouseenter(function() {
    //$("#menu2").offset({ top: top+20, left: left+120 });
    $("#menu2").show();
});

$("#menu2").offset({ top: top+20, left: left+120 });

Check out the Code in Action on Fiddle

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

Achieve an overlapping effect between absolutely positioned sibling divs without the need to specify a background color

Exploring the development of a swipe-to-action list component. <div class="list-container"> <div class="row"> <div class="content"> Sample Content 1 </div> <div class="action"> ...

Implementing a text field to initiate an Ajax request

I need help with triggering my Ajax function whenever a text field is changed. As someone who is new to Ajax, I'm not sure if this is even possible. Any guidance on how to achieve this would be greatly appreciated! Html <form> <a>Ent ...

JQuery UI allows for resizing blocks vertically only, enabling users to adjust the height of

Is there a way to vertically resize a block using jQuery UI? Most examples show resizing by dragging from the bottom of the block, but I specifically need to be able to resize from both the top and bottom directions. ...

Incorporating the use of font color in CSS styles and

I am creating a newsletter template using foundation. Within the table, there are 2 <th> elements containing the content "Reservationnumber" and "23425-FF3234". I have multiple instances of these <th>. I want to apply a colored font to them. Wh ...

Looking for assistance in using JavaScript to determine the percentage of a DIV's width in pixels

Using PHP, I am generating boxes whose width is set to 100% of a container in CSS. Now, I want to determine the equivalent pixel value of that box... HTML <div class="masonry" > <? while($row = $stmt->fetch()){ ?> <div class="i ...

I need assistance with the issue of isset not functioning properly when attempting to upload multiple files

I have been struggling to upload multiple files using various scripts. It works fine most of the time, but occasionally some files fail to upload and I am unable to identify the issue. There is a file containing images, and when I select all the images, t ...

AJAX calls are interrupted due to recursion

On a webpage, I am displaying log files that users can select and delete. The deletion process is carried out through an AJAX request where the ID of each log to be deleted is passed as parameters. However, I have encountered a problem when dealing with a ...

Incorporate a series of interactive buttons within a stylish bootstrap card component

In order to achieve my goal, I am aiming to design a collection of buttons arranged in a grid layout within a bootstrap card element. These buttons should be positioned along the right border of the containing card and remain confined within it. The intent ...

What is the best way to position href text on the top of a rectangular div box?

Whenever I try to position the text above the rectangle, it disables the link. How can I resolve this issue? Additionally, when attempting to change the color of the "San Diego" text, I'm unable to adjust its position. Just a heads up, I am new to HT ...

Are you interested in using jQuery and/or AJAX to retrieve the latest images from a website?

I had to utilize a Wikipedia API in order to retrieve images from the New Jersey website, and I devised two methods to carry out similar tasks. The initial approach involved using JSON, but it ended up pulling the entire page content. <script type="tex ...

The debate between background-image and background: Choosing the right

Experiencing a puzzling issue that seems to have a straightforward solution that I just can't see. I am trying to switch the background to a background-image, but for some reason, the image is not displaying. The code provided below does not show the ...

Leveraging Forms for Entering Google Maps Information

Recently, I've been working on an app that aims to generate a custom map based on user input from a form. If you'd like to test the functionality yourself, head over to this page. After filling out all required fields and hitting "Submit", the g ...

How can the id of the parent element be retrieved within this function?

Is there a way to retrieve the ID of the parent element within the same function and log it in the console? I attempted to obtain the ID of the parent element that I bound the function to. $('#customized-player').mediaelementplayer({ al ...

How to Implement Recursive Function Calls in JavaScript?

My goal is to create an interactive function using HTML and jQuery. I am utilizing jQuery to update and change attributes and text for a more seamless experience without page reloads, especially since it's not image-heavy. I have structured "scenes" ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

CSS unexpectedly adds a border to a div element that does not have any border properties set

Currently, I have a bar with buttons that I refer to as the control bar. My intention is for it to be fixed at the bottom of the screen and span the entire width. However, there seems to be some unwanted white space on the bottom and right edges of the bar ...

The function responsiveTable does not exist

I recently added the following code to my aspx page: <script src="../Scripts/jquery.responsivetable.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#grdStudent').responsiveTable( ...

Is it recommended to utilize sprites for jQuery sliders?

I've heard that utilizing sprites can help improve page load times by reducing the number of HTTP requests. How does this concept apply to jQuery sliders? Do jQuery sliders preload all images upon initial page load, or do they load images as required ...

Creating Consistent Button Padding in Material UI

I am working with a series of Material UI buttons that are defined as follows: <Button className={classes.button}>Edit</Button> <Button className={classes.button}>Duplicate</Button> <hr /> <Button c ...

Is it possible to automatically navigate to a different webpage upon clicking anywhere on the background?

I have created a website with a gif background and I want to redirect to another site (like softlaunch) after clicking anywhere on the screen. This is my HTML and CSS: body { background: url(main.gif) no-repeat center center fixed; -webkit-backgrou ...