Ensuring draggable div remains fixed while scrolling through the page

I am currently working on creating a draggable menu for my website. The menu is functional and can be moved around the page as intended.

However, I have encountered an issue where the menu disappears when scrolling down the page due to its position attribute being set to "absolute" in order to enable dragging functionality.

Is there a way to make the menu stay fixed in place when scrolling or jumping to different sections of the page using hyperlinks?

Note: The menu comprises two divs. Clicking on "menu" reveals various hyperlinks that allow users to navigate through the page.

Thank you for taking the time to read this.

Answer №1

Why is fixed positioning not recommended?

#div_drag {
  position: fixed;
  z-index: 9;
  background-color: #f1f1f1;
  font-family: actor;
  text-align: center;
  border: 1px solid;
  border-radius: 50%;
  width: 70px;
  height: 70px;
  padding: 10px;
  cursor: move;
  top: 60px;
  left: 60px;
}

a {
  text-decoration: none;
  color: black;
}

a.color {
  color: white;
}

.test {
  background-color: blue;
  height: 900px;
}
<html>

<head>
  <link rel="stylesheet" href="test.css" type="text/css">
  <link href='https://fonts.googleapis.com/css?family=Actor' rel='stylesheet'>
  <script src="jquery-3.3.1.min.js"></script>
  </link>
</head>

<body>


  <div id="div_drag">

    <a onclick="document.getElementById('div_name2').style.display='';return false;" href=""><br>menu</a>

    <div id="div_name2" style="display:none;position: absolute;z-index: 10;background-color: black;font-family:actor;text-align center;width:170px;height:170px;padding: 10px;cursor: move;top:-20px;left:-20px;">

      <a href="firstyear.html" class="color">+2018</a>
      <br></br>
      <a href="#1" class="color">1</a>
      <a href="#2" class="color">2</a>
      <a href="#3" class="color">3</a>
      <a href="secondyear.html" class="color">+2017</a>
      <br></br>
      <a href="thirdyear.html" class="color">+2016</a>
      <br></br>
      <a href="fourthyear.html" class="color">+2015</a>
      <br></br>

      <a onclick="document.getElementById('div_name2').style.display='none';return false;" href="">hide</a>
    </div>
  </div>

  <script>
    dragElement(document.getElementById(("div_drag")));

    function dragElement(elmnt) {
      var pos1 = 0,
        pos2 = 0,
        pos3 = 0,
        pos4 = 0;
      if (document.getElementById(elmnt.id + "header")) {
        /* if present, the header is where you move the DIV from:*/
        document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
      } else {
        /* otherwise, move the DIV from anywhere inside the DIV:*/
        elmnt.onmousedown = dragMouseDown;
      }

      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }

      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        // set the element's new position:
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
      }

      function closeDragElement() {
        /* stop moving when mouse button is released:*/
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
  </script>


  <div class="test">
    <a name="1"></a>
    hello!
  </div>

  <div class="test">
    <a name="2"></a>
    hello!
  </div>

  <div class="test">
    <a name="3"></a>
    hello!
  </div>



</body>

</html>

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

Tips for implementing a sticky sidebar in HTML5 with jQuery

I currently have two files: index.php and aside.php. I've already created the contents of aside.php. Now, I want to make the aside page sticky. To achieve this, I referred to the following link: http://codepen.io/pouretrebelle/pen/yvcBz My struggle ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

When the React functional component changes its state, it triggers the un-mounting and re-mounting of its parent

I created a functional component that allows for toggling the visibility of a password field using a small button that switches between closed and opened eye images. The issue I'm facing is that even though the parent does not have any affected state ...

Trouble With Ajax Submission in CakePhp: Issue with Form Serialization

In my attempt to utilize ajax for sending an array of objects along with serialized form data, I encountered a problem. The issue arises when I include the array in the ajax data along with the serialized form data. This results in the serialized form data ...

Transforming JSON data into XML using Angular 7

It turns out the xml2js npm package I was using doesn't support converting JSON to XML, which is exactly what I need for my API that communicates with an application only accepting XML format. In my service file shipment.service.ts import { Injecta ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

TSLint is encountering the error code TS2459: The module "@azure/core-tracing" claims to have a local declaration of "Span" but does not export it, along with additional errors

I'm completely lost on how to tackle this error. The message I'm getting doesn't provide much insight, other than indicating an issue with the installation of '@azure/ai-text-analytics'. I've gone through the process of uninst ...

The HTML source code in the browser varies from the output obtained through Python requests

I've noticed a discrepancy between the HTML source code displayed in my browser and the code I receive when using Python's requests.get function. You can see the image depicting this issue at the following link: Any thoughts on why this might be ...

Issues with the Bootstrap date time picker functionality

Even though I have added all the necessary libraries for the date time picker, it still isn't working properly. You can check out this fiddle to see the code. <div class='input-group date' id='from_time'> <input type ...

Determining if an item is located within a nested scroll container

How can one detect if a specific element within a scrollable container is currently visible to the user's view (i.e. within the visible area of the scrolling parent)? Is there a universal method available that does not require iterating through all p ...

Import the information into a td tag's data-label property

I have implemented a responsive table design that collapses for smaller screens and displays the table header before each cell. body { font-family: "Open Sans", sans-serif; line-height: 1.25; } table { border: 1px solid #ccc; border-collapse: co ...

Does the AngularJS Controller disappear when the DOM element is "deleted"?

One challenge I encountered is regarding a directive that is connected to an angularjs controller, as shown below: <my-directive id="my-unique-directive" ng-controller="MyController"></my-directive> In the controller, at a certain point, I ne ...

Using Angular to open a modal by invoking the href function

Current Project Context I am currently following a tutorial on CRUD operations with DataTables, but I am using Asp.Net WebApi with Angular for this project. At step 9 of the tutorial, it introduces partial views for pop-up windows. However, instead of us ...

Creating personalized hooks that rely on React query requests

Utilizing a series of custom hooks, I am able to fetch data and perform various calculations based on that data. One particular hook calculates the total amount that should be set aside monthly for future expenses, using the output from previous data-fetch ...

Rails is being overwhelmed by an excessive number of icons being added by Bootstrap

I'm having an issue with adding a user icon to my header. When using Bootstrap, it seems to be adding more icons than I have specified in my code. Can anyone help me figure out what's going on? Thanks in advance! <ul class="nav pull-right"> ...

Vue-bootstrap spinbutton form with customizable parameters

I am in need of a custom formatter function for the b-form-spinbutton component that depends on my data. I want to pass an extra argument to the :formatter-fn property in the code snippet below, but it is not working as expected. <b-form-spinbutton :for ...

LESS — transforming data URIs with a painting mixin

Trying to create a custom mixin for underlining text, similar to a polyfill for CSS3 text-decoration properties (line, style, color) that are not yet supported by browsers. The idea is to draw the proper line on a canvas, convert it to a data-uri, and the ...

jQuery sends ajax success to input type number

I am encountering an issue with the ajax success loading function when using input type number. Interestingly, when I switch the input type to text, it works perfectly fine. However, once I change the input type back to number, the loading ceases. <s ...

How to send parameters to Bootstrap modal using a hyperlink

I need help confirming the deletion of a datatable row using a Bootstrap modal dialog. When a user clicks on the delete link, I want a modal to appear asking for confirmation. Here is my code: <c:forEach items="${equipes}" var="equ"> ...