Tips for identifying if the cursor is hovering over the :before or :after section of an element

One of the challenges I am facing involves CSS and defining drop areas for users to interact with, allowing them to either drop a section before or after existing sections.

.section:before,
.section:after {
    content: "[insert here]";
    height: 64px;
    line-height: 56px;
    width: 100%;
    display: block;
    border: 3px dashed #aaa;
}

In order to address this issue, I have implemented a JavaScript + JQuery listener to detect the element currently under the mouse:

elem.on('drop', function(e) {
  e.preventDefault();

  var container = $(elem[0].elementFromPoint(e.clientX, e.clientY));
});

The problem arises when container ends up being the same element regardless of whether it is dropped before or after the section.

I am seeking a solution to determine if the user has dropped before or after the section. Any insights on how to achieve this would be greatly appreciated.

Answer №1

In the realm of CSS, ::before and ::after pose as pseudo-elements unknown to JavaScript. In JavaScript's perspective, they are merely seen as part of their parent element.

To achieve similar effects in JavaScript, it is recommended to utilize actual HTML elements instead.

Answer №2

The pseudo-elements :before and :after exist outside of the DOM, making them inaccessible to Javascript.

One potential workaround is to measure the height of the section and then analyze how its drop coordinates align with x and y values to ascertain if it was dropped before or after.

Answer №3

It is not possible to manipulate the pseudo elements ::before and ::after since they do not exist in the DOM, making them inaccessible by JavaScript.

Answer №4

Yes, this can be achieved.

(Although -- as pointed out by others -- it may not be the most ideal approach)

If we consider that the content is arranged vertically with: before -> content -> after

We can determine the drop point in relation to the container and then, based on the height of the generated content, ascertain whether the element was dropped before or after the designated zone.

Furthermore, javascript has the capability to access css properties of pseudo-elements.

This can be done using Window.getComputedStyle()

Syntax: (from MDN)

var style = window.getComputedStyle(element[, pseudoElt]);

pseudoElt Optional

A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.

For example, to retrieve the height of the generated content before a section (referred to as 'target'):

window.getComputedStyle(target, ':before').height 

Check out this Demo snippet:

var elem = document.getElementById("el");
var target = document.getElementById("target");
  
var targetHeight = parseFloat(window.getComputedStyle(target).height);
var beforeHeight = parseFloat(window.getComputedStyle(target, ':before').height);
var afterHeight = parseFloat(window.getComputedStyle(target, ':after').height);

elem.addEventListener("drag", function(e) {
  document.body.classList.remove('dropped');
});

target.addEventListener("dragover", function(e) {
  this.textContent = "dragging over section";
  document.body.classList.add('dragging-over');
  addBeforeAfterClasses(e);
});

target.addEventListener("dragleave", function(e) {
  document.body.classList.remove('dragging-over');
  this.textContent = "section";
  e.currentTarget.style.background = "none";
});

target.addEventListener("drop", function(e) {
  document.body.classList.add('dropped');
  addBeforeAfterClasses(e);
  this.textContent = "successfully dropped!";
});

function addBeforeAfterClasses(e) {
  var dropOffsetTopWithRespectToContainer = e.clientY - target.offsetTop;
  if(dropOffsetTopWithRespectToContainer <= beforeHeight) {
    document.body.classList.add('before');
  } else {
    document.body.classList.remove('before');
  }
  if(dropOffsetTopWithRespectToContainer > targetHeight - beforeHeight) {
    document.body.classList.add('after');
  } else {
    document.body.classList.remove('after');
  }
}

target.ondrop = drop_handler;
target.ondragover = dragover_handler;

function drop_handler(e) {
  e.preventDefault();
}

function dragover_handler(e) {
  e.preventDefault();
}
.section {
  margin: 10px;
  position: relative;
}
.section:before,
.section:after {
    content: "[insert here]";
    height: 64px;
    line-height: 56px;
    width: 100%;
    display: block;
    border: 3px dashed #aaa;
}

.dragging-over.before .section:before {
  content: "[drop into before]";
  border-color: green;
}

.dragging-over.after .section:after {
  content: "[drop into after]";
  border-color: green;
}

.dropped.before .section:before {
  content: "[dropped into before]";
  background-color: green;
  color: white;
}

.dropped.after .section:after {
  content: "[dropped into after]";
  background-color: green;
  color: white;
}

.elem {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: maroon;
  margin: 0 20px;
  display: inline-block;
}
<div id="target" class="section">section</div>
<span>drag me:</span>
<div id="el" draggable="true" class="elem"></div>

View Codepen demo

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

Guide on making a personalized object in JavaScript

I am struggling with a piece of JavaScript code that looks like this: var myData=[]; $.getJSON( path_url , function(data){ var len = data.rows.length; for (var i = 0; i < len; i++){ var code = data.rows[i].codeid; var ...

Do you require assistance with creating an image slideshow?

My first day working with HTML was a success as I successfully built a navigation bar that looks pretty cool. Take a look at it here. Next on my list is to incorporate a slideshow into my site, possibly using JavaScript or jQuery plugins. I'm aiming ...

Need a hand with ajax?

Recently, I've been having issues with a PHP script that packages files into a zip based on user input. Unfortunately, the server occasionally errors out and causes all the form data to be lost. To prevent this from happening in the future, I was info ...

The URIError occurred while attempting to decode the parameter '/December%2015,%' within the express framework

After setting up a middleware using the express framework that handles a URI with a date as a parameter, I encountered a small issue. app.get("/:date",function(req,res){ var result; var myDate=req.params.date if(moment(myDate).isValid()) ...

Ensure that each item rendered in a VUE.js v-for loop is distinct and not repetitive

I have obtained a JSON formatted object from a Web API that contains information about NIH funding grants. Each grant provides a history of awards for a specific researcher. My goal is to display only the latest award_notice_date for each unique project ...

The download button consistently targets and downloads the initial SVG in my collection. How can I configure it to target each individual SVG for download?

I'm currently working on a QR code app using React. The goal is for users to submit a form with a value, which will then generate an SVG QR code that can be downloaded. However, I'm running into an issue where the same SVG file is being downloade ...

Issue with collapsing custom-height navigation bar in Bootstrap 4

I have implemented a Bootstrap 4 navbar with a brand logo image sized at 150px x 33px. Now, I want to increase the height of the navbar to 80px. To do this, I added min-height: 80px; in my CSS. <!DOCTYPE html> <html lang="en"> <head> ...

How can I determine the remaining amount of scroll left in my HTML document?

Is there a method to determine how many pixels of scroll remain on the page when the scrollbar is set at a specific position? I am currently utilizing jQuery's scrollLeft feature, which can be found here: http://api.jquery.com/scrollLeft/. I want to ...

fancybox thumbs will never function properly

I recently made the switch from using PrettyPhoto to FancyBox for my gallery, which utilizes Isotope for filtering and animations. However, I am encountering an issue where the images appear but the thumbnails are missing. In the developer tools, there is ...

Are elements loaded and hidden by ng-hide and ng-show, or does loading only occur with ng-show?

Is this method of programming effective for handling large elements such as 10 mb images? Are there alternative solutions that would work better? ...

Is it possible to implement a personalized "Loading..." div in Fancybox 2?

Despite searching extensively, I have not been able to find a solution or any reference in the documentation at : Is there an option to substitute my own custom div in place of the loader GIF during the loading process when Fancybox is waiting for content ...

Utilizing Jquery's replacewith function to extract and read the id value

In this script, changing the dropdown list populated with opt1/opt2 triggers an alert displaying the ID as 'drop'. However, when I click on the 'clickme' text entry box, it transforms into a new dropdown. Yet, there is no alert issued ...

Having difficulty injecting $timeout into an AngularJS controller within the app

Recently, I've started working with Angular JS on a game development project. One of the requirements is to call a function after a timeout. After some research, I found out about the $timeout feature provided by AngularJS, so I tried injecting it int ...

PLupload does not support Flash runtime in Internet Explorer 8

I am facing a dilemma with a basic JavaScript function placed within the $(function() { ... }); block. var uploader = new plupload.Uploader({ runtimes: 'html5,flash,silverlight', browse_button: 'pickfiles', c ...

Sorting data in Javascript can be done efficiently by utilizing the .filter method

Can someone help me identify what I might be doing incorrectly? I have a chained filter under computed that is giving me an error message stating 'product.topic.sort' is not a function. My intention is to use 'select' to provide sortin ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...

Why is inner HTML returning input/textbox instead of the value?

I need help extracting the value from an input/textbox within a table cell. Although the rest of my code is functioning correctly, I'm struggling to retrieve the value from this particular input element. I've attempted to access the value using ...

The div functions seem to stop working properly after they have been multiplied

Initially, I use JavaScript to multiply the div but then encounter issues with the function not working properly. function setDoorCount(count) { $('.doors').html(''); for (var i = 0; i < count; i++) { var content = " ...

Managing Numerous Dropdown Menus: Techniques and Tips

I'm currently working with MUI to design a navigation menu that contains dropdowns within certain links. However, I've encountered an issue where clicking on any button opens the same dropdown menu. Below is my code snippet: function Header() { ...