The function insertAdjacentHTML places elements after the parent container instead of after the specific div contained within

As I work with a basic U.S. map, I encounter the need for fixed positioning of both the map and state abbreviations on it. User input triggers database queries, and based on query results, I change the class of state abbreviations to format them like buttons. The main objective is to create a div below the button that holds information related to the specific state. However, an issue arises where this div appears after the container holding the map. CSS

<style>
    #MapContainer {position:absolute; width:1760px; height:1099px; top:0; left:0; padding:0; z-index:1;}
    .Abr {position:absolute; font-size:18px; font-weight:bold; color:#006393; z-index:100}
    .Active {background:red; padding:6px; color:white; border:1px solid black; border-radius:50%;}
</style>

HTML with PHP (Demonstrated for one state)

<div id="MapContainer">
    <img src="maps/TransUSA-All50-1760x1099.png" style="width:100%" />
    <div class="Abr" id="WA" style="top:100px; left:238px;">WA</div>
    // Database queries go here once all state names are defined
    while($Info = i5_fetch_array($Result))
   {
     switch($Info[STATE])
       {
         case "WA":
          echo('<script>$("#WA").addClass("Active"); var Rates = "'.$Info[Rates].'"; var Charges = "'.$Info[Charges].'";</script>');
        break;
  //etc.
 }
  </div> 
 

The challenge lies in ensuring the data div appears directly under the state abbreviation button rather than at the end of the map container when clicked. jQuery

<script type="text/JavaScript">
    $(".Active").on("click", function()
    {
       this.insertAdjacentHTML("afterend","<div>This is a data Div</div>");
    });
</script>

Despite efforts, the appended div consistently displays at the bottom of the map container instead of right under the "WA" abbreviation button.

Check out the example:

<div id="MapContainer">
    <div id="WA">WA</div>
    // The data div should be located here
</div>
// Yet, it shows up here


___________________________________________________
|                                                 |
| <div>WA</div>                                |
| <div>Data div should appear here</div>      |
|                                                 |
|_________________________________________________|
<div>Data div appears here instead</div> 
 

I have prepared a fiddle Here. Unfortunately, even there, the data div ends up inside the map block instead of below it.

Final Outcome On reaching the final outcome, I realize certain limitations exist due to fixed positioning causing overlap issues between active buttons and info boxes for neighboring states.

https://i.sstatic.net/3OgOK.png

https://jsfiddle.net/RationalRabbit/rj8g2bqm/87/

A solution involved using a screenshot of the map background with the abbreviations included, removing abbreviations from span sections, and adding them back when a state becomes active. Some adjustment was also needed in the rendering order to prevent overlapping occurrences. This indicates that the initial problem might have been resolved by changing the order of abbreviation definitions in the first place. For instance, reordering "ID" before "OR" might have addressed the issue upfront.

Answer №1

Take a look at the code snippet below, I have also shared it on Codepen for easy access: Positioned DIVs for MAP

$(document).ready(function () {
    $("#WA").addClass("Active");
    $(".Active").on("click", function (e) {
        var $this = $(this), $data = $this.next('.AbrData');
        var ST = "AK"; // You can retrieve this from the state div along with the data
        if ($data.length == 0) {
            $data = $("<div class='AbrData'></div>").insertAfter($this);
            $data.append('<div id="' + ST + 'Data">This is a data Div</div>');
        }
        else {
            $data.toggle();
        }
    });
});
#MapContainer {
    position: absolute;
    width: 700px;
    height: 400px;
    top: 10px left 10px;
    padding: 0;
    z-index: 1;
    border: 2px solid black;
}

.Abr {
    position: absolute;
    font-size: 18px;
    font-weight: bold;
    color: #006393;
    z-index: 100;
}

.AbrData {
    position: relative;
    top: 10px;
    font-size: 12px;
    color: blue;
    z-index: 101;
    max-height: 100px;
    overflow: auto;
    border: 1px solid grey;
}

.Active {
    background: red;
    padding: 6px;
    color: white;
    border: 1px solid black;
    border-radius: 50%;
    cursor: pointer;
}
<div id="MapContainer">
    <div class="Abr" style="top:100px; left:238px;">
        <span id="WA">WA</span>
    </div>
    <div class="Abr" style="top:213px; left:207px;">
        <span id="OR">OR</span>
    </div>
    <div class="Abr" style="top:315px; left:550px;">
        <span id="WY">WY</span>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I have incorporated the recommended modifications, and now the line that appears after toggling the data is the border of div.AbrData. The toggle line has been updated to toggle div.AbrData itself instead of its internal content.

// Updated the toggle functionality
$("#"+ST+"Data").toggle();

// To this
$data.toggle();

Answer №2

Just to clarify, insertAdjacentHTML is not a feature of jQuery, but rather a method belonging to DOM elements. Take a look at the example below to see how it can be used:

var div = document.querySelector('#idDiv');
div.insertAdjacentHTML('beforebegin', '<p>beforebegin</p>');
div.insertAdjacentHTML('afterbegin', '<p>afterbegin</p>');
div.insertAdjacentHTML('beforeend', '<p>beforeend</p>');
div.insertAdjacentHTML('afterend', '<p>afterend</p>');

console.log(document.querySelector('#container').outerHTML);
div {
  color: blue;
  border: 1px solid blue;
  padding: 5px;
}
p {
  color: red;
  border: 1px solid red;
  padding: 5px;
}
<div id="container">
<div id="idDiv">ORIGINAL HTML DIV CONTENT</div>
</div>

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

Using jQuery to toggle visibility of various elements without needing specific identifiers

I have coded a HTML and JS snippet for displaying and hiding a div element, which is currently functioning correctly. However, I want to be able to use multiple boxes on a single page and I need a way to determine which box-header was clicked. Is there a ...

What is the reason for the consistency in the effects of vertical align: text bottom and vertical align: bottom?

The baseline positioning of a line box is impacted by all elements within that line. .short-box { width: 30px; height: 30px; background-color: pink; display: inline-block; } .box { background-color: ...

The script is failing to execute in a modal dialog box

Can anyone help troubleshoot why this script isn't functioning properly in a modal window (PrettyPhoto)? I've attempted jQuery(document.body).ready(function(){ instead of $(function() { but I'm encountering the same issue: the script wor ...

Acquire JSON data using a Bearer token

I am facing an issue with my getJSON script that normally outputs JSON strings. However, it seems to be failing when using a Bearer Token API. Even though I have included the Bearer Token in my HTTP Header like this: authorization: Bearer Mytoken I am no ...

What is the best way to display a User's name as text on a Django page without having to refresh the page?

I'm currently working on a feature where I need to show a User's name on top of a form box when they enter their Employee number, all without needing to refresh the page. Here's how it should work: once the User fills in their Employee numb ...

Displaying information in a modal using the function $('#MyModal').modal('show');

Dygraphs is a fantastic tool that simplifies the process of transforming JSON data into interactive charts on an HTML page. With Dygraphs, it's easy to add annotations to your charts with custom click events: annotations.push({ series: "@Model.P ...

Load data into data tables through AJAX request

I'm currently working on implementing datatables and I'm facing an issue with populating my data table using an AJAX call. Here is the snippet of my AJAX call: $('#call_analysis_basic_table').DataTable ({ "ajax": { "url": " ...

What is the best method for choosing elements when I already possess a DOM element?

When you have a variable that contains a DOM element and need to select related elements, you can easily achieve this by wrapping it in a jQuery object. var myDomElement = document.getElementById("foo"); $(myDomElement ).find("a"); It is common for peopl ...

The JQuery code that I designed is causing a significant decrease in performance specifically in IE7, while other browsers are not

As this is my first time asking a question on this platform, I apologize if I come across as inexperienced with the rules (even though I quickly familiarized myself with them). Now, onto the issue at hand. I have created a customized menu in SharePoint 2 ...

When making a jQuery call to a WCF service, I received a 200 Parser Error

I'm new to the world of WCF. I have a solution that includes a Web App (with a JQuery Ajax call to a WCF services application in another project within the same solution). After working on it for 2 days, I am now able to pass requests and receive resp ...

Tips for capturing the colorbox opening event with jQuery

While my knowledge of jQuery is very basic, I am faced with a problem that needs solving. On my Drupal-based webpage, I have integrated a map that opens in Colorbox using the Colorbox Node module. There is a hyperlink on the page that triggers this action: ...

Shifting the final child to the front position proves unsuccessful with jQuery

I have attempted to move the last element in my list to the first position upon clicking, but unfortunately, it is not working as expected. I followed the advice provided in response to a question on the following page: Move last child to first position. W ...

Tips for displaying unformatted text using HTML

Is there a way to display a string in HTML with all of its escape sequences preserved? For example: eipt No. : 1995,\nmount 935\nAdm. : 17/06/2016 INSTRUCTIONS : 1) This card is valid only for the student's name & for the period indic ...

How to trigger a function in JavaScript only once

On my webpage, I added a radio button that allows users to choose between Metric or Imperial units. Below is the code for the event handler: var metricRadio = document.getElementById("metric"); var imperialRadio = document.getElementById("imperial"); met ...

Shopping Dialog with Bootstrap (nakupanda) captures form input [JSFiddle]

Having difficulty extracting data from my form. Currently utilizing the bootstrap dialog from nakupanda () The dialog (located within a fullcalendar select function) var form = $('#createEventForm').html(); BootstrapDialog.show({ mes ...

Issue with F12 Functionality: Unable to Navigate to CSS Definitions within CSHTML Files in Visual Studio 2017

Currently, I am in the process of developing my very first Asp.net Core 2.0 Mvc website. While I typically rely on web forms, I decided to venture into something new. In my .cshtml files, I have encountered a limitation where I am unable to F12 or right-c ...

Unable to populate SQL Server database from PHP JQuery form

I am facing an issue where hitting save just refreshes the page with a different URL added. Uncertain if it's due to my query or if the form data is not being submitted correctly. require_once ('connectionstring/connectionstring.php'); $con ...

Javascript is utilized to populate text within a div, although the animation is exclusively applied to the initial text

I am currently working on designing a landing page that showcases a dynamic display of rotating texts with a typewriter-like animation effect. While I have successfully implemented the animation for the first text, I am facing an issue where the subsequent ...

Adding a fresh data point to Highcharts

Can the highchart line graph be updated every minute without starting from scratch? I want it to add new data points to the existing line, similar to the example shown in this jsfiddle. $(function () { $.getJSON('https://www.highcharts.com/sample ...

What could be causing the failure of -moz-binding in my code?

I am encountering an issue with a file named SolarCalendar.htc. Here are the contents of this file: <script language="javascript"> //My java Script Code </script> <public:property put=fnPutDay get=fnGetDay n ...