Steps for creating a div that appears on top of all other elements on a webpage

I have created a custom dropdown list with checkboxes from scratch because the project I am working on needs to be compatible with older versions of IE. Overall, the result is good but there is one issue - when I click on the drop down list, every other element on the page shifts downwards.

What I want to achieve is for the dropdown list to behave like a select element where it appears on top of all other elements on the page. Is there a CSS property or pure JavaScript solution that can help me achieve this?

Here is the code snippet:

var checkList = document.getElementById('list1');
var items = document.getElementById('items');
document.getElementById('anchor').onclick = function(evt) {
  if (items.className.indexOf("visible") !== -1) {
    items.className = "";
    items.style.display = "none";
  } else {
    items.className = " visible";
    items.style.display = "block";
  }


}
.dropdown-check-list {
  display: inline-block;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
}

.dropdown-check-list ul li {
  list-style: none;
}
<body>
  <div id="list1" class="dropdown-check-list" tabindex="100">
    <span id="anchor" class="anchor">Type</span>
    <ul id="items" class="items">
      <li><input type="checkbox" />Choice 3</li>
      <li><input type="checkbox" />Choice 2</li>
      <li><input type="checkbox" />Choice 1</li>
    </ul>
  </div>
  <h1>
    this shou
  </h1>
</body>

Answer №1

Employ the use of position:absolute for the checklist to remove it from the document flow, ensuring it does not affect other elements...

Additionally, apply position:relative to the parent container .dropdown-check-list

const checkList = document.getElementById('list1');
const items = document.getElementById('items');
document.getElementById('anchor').onclick = function(evt) {
  if (items.className.indexOf("visible") !== -1) {
    items.className = "";
    items.style.display = "none";
  } else {
    items.className = " visible";
    items.style.display = "block";
  }


}
.dropdown-check-list {
  display: inline-block;
  position: relative;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
  position: absolute;
  left: 0;
  right: 0;
  background: #fff;
  top: 100%;
}

.dropdown-check-list ul li {
  list-style: none;
}
<body>
  <div id="list1" class="dropdown-check-list" tabindex="100">
    <span id="anchor" class="anchor">Type</span>
    <ul id="items" class="items">
      <li><input type="checkbox" />Choice 3</li>
      <li><input type="checkbox" />Choice 2</li>
      <li><input type="checkbox" />Choice 1</li>
    </ul>
  </div>
  <h1>
    this shou
  </h1>
</body>

Answer №2

Here is my modest contribution:

var addButton = document.getElementById("add");
addButton.onclick = addDropdown;
for (var i = 0; i < 8; i++) {
  addDropdown.call(addButton);
}

document.addEventListener("click", function (ev) {
  var el = ev.target;
  if (hasClass(el, "dropdown")) {
    let list = closestDropdownList(el);
    if (hasClass(el, "active")) {
      list.style.display = "none";
      removeClass(el, "active");
    } else {
      var t = el.offsetTop;
      var l = el.offsetLeft;
      var h = el.offsetHeight;
      list.style.left = l + "px";
      list.style.top = t + h + "px";
      list.style.display = "block";
      addClass(el, "active");
    }
  }
});

document.addEventListener("blur", function (ev) {
  var el = ev.target;
  if (hasClass(el, "dropdown")) {
    let list = closestDropdownList(el);
    list.style.display = "none";
    removeClass(el, "active");
  }
}, true);

function addDropdown () {
  var els = [];
  var el = this;
  var parent = this.parentNode;
  while (!hasClass(el, "dropdown")) {
    el = el.previousSibling;
    els.push(el.cloneNode(true));
  }
  while (els.length > 0) {
    parent.insertBefore(els.pop(), this);
  }
}

function hasClass (el, name) {
  if (!el.getAttribute) {
    return false;
  } else {
    var attr = el.getAttribute("class");
    attr = " " + attr + " ";
    name = " " + name + " ";
    return attr.indexOf(name) >= 0;
  }
}

function removeClass (el, name) {
  var attr = el.getAttribute("class");
  attr = " " + attr + " ";
  name = " " + name + " ";
  attr = attr.replace(name, " ");
  attr = attr.slice(1, -1);
  el.setAttribute("class", attr);
}

function addClass (el, name) {
  var attr = el.getAttribute("class");
  attr += " " + name;
  el.setAttribute("class", attr);
}

function closestFollowing (el, predicate) {
  while ((el = el.nextSibling) && !predicate(el));
  return el;
}

function closestDropdownList (el) {
  return closestFollowing(el, function (sibling) {
    return hasClass(sibling, "dropdown-list");
  });
}
.dropdown {
  margin-bottom: .5em;
}
.dropdown:after {
  content: "";
  margin-left: .4em;
  display: inline-block;
  vertical-align: middle;
  border-top: 5px solid black;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-bottom: 0px;
}
.dropdown-list {
  border: 1px solid black;
  position: absolute;
  background: white;
  display: none;
  padding: .2em;
  margin: 0;
}
.dropdown-list li {
  list-style: none;
  cursor: pointer;
  padding: .25em;
}
.dropdown-list li:hover {
  background: #ddd;
}
<button class="dropdown">Choose</button>
<ul class="dropdown-list">
  <li>Option A</li>
  <li>Option B</li>
  <li>Option C</li>
</ul>
<button id="add">Add dropdown</button>
<p>Greetings World! Greetings World! Greetings World!</p>

Utilizing event delegation for "focus" and "blur": quirksmode.org.

Answer №3

To make the div stand out, set its z-index to 2, while the rest of the elements should have a z-index of 1.

Remember, the higher value takes precedence and appears in the front.

Answer №4

To obtain this effect, you can apply the CSS property position: absolute to the items:

.items {
    position: absolute;
    background: #ffffff;
}

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

Exploring the world of interconnected meshes in three.js

Currently, I am in the process of working on 3D models for a project using three.js. The model I am creating is a combination of basic geometries that come together to form a defense tower. Specifically, I have 2 Boxes and 3 Cylinders that make up the st ...

JavaScript and inverted brackets

Why does Javascript allow the use of inverted parentheses in function calls? I'm currently using a Node console on the CLI with Node version 0.10.25. function a(){ return 42 } a() // -> 42 a)( // -> 42. Strange behavior? function b(t){ return ...

Performing a Node.js PATCH request that includes the If-Match header

I have a question that has been puzzling me for some time now. While working with Node.js and creating a PATCH request, I want to set the if-match header to *. Is the code snippet below the correct way to do it? Will this actually work? headers: { &a ...

Displaying live data from an XMLHttpRequest in a Vue component in real-time

I'm currently working on implementing lazy loading for a list of posts fetched from the WordPress REST API. My goal is to load additional news stories upon clicking an HTML element. However, I'm facing issues with accessing the original Vue inst ...

Why isn't httpUploadProgress functioning correctly with Buffer data?

Recently, I have ventured into the world of node.js/express as I am attempting to create a multiple image uploading application utilizing cloudfront and an s3 bucket. My goal is to display a progress bar for the user by integrating socket.io for real-time ...

Parsing error: Unexpected character found at line 238, column 16. Consider using a loader suitable for this file format

Currently, I am attempting to integrate ArcballControls.js controls into my Vue.js application. I've noticed that this particular class contains functions that utilize arrow syntax, whereas every other class in the controls does not. This seems to be ...

Tips for creating row grouping in React JS

Currently, I am working on a React application and I would like to incorporate grouping similar to what is shown in the image. I have looked into row grouping but it doesn't seem to be exactly what I need. How can I go about implementing this feature? ...

Searching for data between two specific dates can be achieved in Laravel Vue by utilizing the filter

I've successfully implemented a search feature for normal fields in my form. However, I'm encountering difficulty when trying to search within a date range. Here's my controller code: public function index() { $query = Matter::query(); $qu ...

Storing a chosen avatar in a database: A step-by-step guide

I am looking to display a selection of 10 avatars on my website for users to choose from. There will be no option for users to upload their own avatar. Users will simply click on the avatar image they want and then click the "done" button. The selected ava ...

jquery:Error: string literal not properly terminated

Every time I add a space between a word and click to call a function, I encounter the following error: SyntaxError: unterminated string literal [Break On This Error] $(this).SelectProjectBox(363,"ssss mypage# (line 1, col 29) HTML generated by the b ...

What is the best way to show a list when hovering the mouse over a

<nav> <a href="login.html" class="dropdown-content" style="text-align: center"><span id="login">您好</span><i class="login"></i></a> <a href="9.html"><i class="like"></i></a> <a href="7 ...

Symfony2 requires clarification and direction when it comes to managing quantities in a shopping cart

My current challenge involves managing quantities in a shopping cart. I can easily add, delete, and view products in the cart, but am struggling with increasing or decreasing quantities if a user wants to purchase multiple units of the same product. BACKG ...

Issue with sorting dates when there is an extra digit in the budget, for example: "02/13/2017 0"

Currently, I am utilizing the tablesorter plugin to sort through my table data. One of the columns in the table contains dates along with an additional badge digit. For instance, "02/13/2017 0". I am specifically interested in sorting this column based o ...

Dealing with 401 Errors: Navigating Redirects using Vue.js and

Currently, I am utilizing Vue.js along with axios in an attempt to create a generic API object as shown below: import router from './router' import auth from './auth' const axios = require('axios') export const API = axios.c ...

If you encounter an unrecognized operator in Javascript, make sure to handle this error and return

I have a script that identifies operators in an array and uses them to calculate based on another array. Below is the script: function interpret(...args) { let operators = args[1]; //access the operators array let values = args[2] //numbers except t ...

Maintaining and refreshing the content in an input field

I'm currently working on a JavaScript program that aims to update the value of a hidden input field. However, I am facing an issue where a specific value is being changed too frequently. To address this, I have attempted using the following method to ...

Triggering multiple functions by clicking on the Icon

I'm trying to execute two different functions when the user clicks on the Icon, but I keep getting an error that says: Expected onClick listener to be a function, instead got a value of object type. Can someone please help me figure out what I am doin ...

"Discover how simple tips can enhance your website's user experience by enabling

I am attempting to retrieve content from the database using simpletip. Here is my code: <script type="text/javascript"> $(document).ready(function(){ $('a.regularsList').simpletip({ onBeforeShow: function(){ ...

Create a variety of documents and bundle them into a zip file for easy

I'm currently implementing docx.js in my react application running on AWS Amplify (using a node backend). I am creating multiple documents and saving them individually by utilizing the packer to produce the document as a blob, then using the FileSaver ...

What is the reason for the gap between the bottom row and the one above it?

Using bootstrap to create a table and my code is as follows: <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> ...