Utilize JavaScript to trigger a gentle notification window to appear on the screen

Whenever I click a link on my HTML page, I want a popup element (just a div box) to appear above the clicked link. I have been using JavaScript for this, but I am facing an issue where the popup element appears below the link instead of above it.

Can you point out what I might be doing wrong and suggest a solution?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/homepage.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>

    <style type="text/css" media="all">
        <--

        html, body, div, form, fieldset, legend, label, img {  margin: 0;  padding: 0;  }  table {  border-collapse: collapse;  border-spacing: 0; }  th, td {  text-align: center;  }  h1, h2, h3, h4, h5, h6, th, td, caption { font-weight:normal; }  img { border: 0; } 

        body { padding: 20%; background-color: green; }

        .container { background-color: white; }
        .newEle { width: 100px; height: 100px; background-color: red; }

        -->
    </style>
    <script type="text/javascript">

        function getOffset( el ) 
        {     
            var _x = 0;
            var _y = 0;

            while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) )
            {
                _x += el.offsetLeft - el.scrollLeft;
                _y += el.offsetTop - el.scrollTop;
                el = el.parentNode;
            }     

            return { top: _y, left: _x }; 
        }  

        function onClick( n, ele )
        {
            // Should display a popup box just above the HTML element called "ele"
            // but what actually happens is that the box is displayed below the element
            // called "ele"

            var infoBox = document.createElement("div");

            infoBox.style.zIndex          = "5";
            //infoBox.offsetRight           = ele.offsetRight;
            //infoBox.offsetBottom          = parseInt(ele.offsetBottom, 10) - 200 + "px";
            infoBox.style.x                     = getOffset( ele ).left + "px";
            infoBox.style.y                     = getOffset( ele ).top  - 200 + "px";
            infoBox.style.width           = "200px";
            infoBox.style.height          = "200px";
            infoBox.style.backgroundColor = "blue";
            infoBox.innerHTML             = "Hello";

            document.body.appendChild( infoBox );
        }

    </script>
</head>

<body>

    <div class="container">
        <a class="newEle" onclick="onClick(1,this)">Create New Element</a>
    </div>

</body>
</html>

Answer №1

Include the following code in your CSS file.

.container, .newEle {display: block; float: left;}

Afterwards, use absolute positioning for your elements.

Answer №2

(Apart from the post by Carl Griffiths, consider this as well)

Upon reviewing your code, the reason why it appears below your link is:

  1. You are appending the new element after your div.
  2. You mentioned having x and y styles, but they are not being applied to that element. (Use firebug for FF or developer-tools in Chrome)
  3. If you successfully add the position style to the new element, your next challenge is that it may not be visible on the page. For example, if you set the top position to -200px, it will be positioned relative to your body rather than your link.

Possible Solution:

  1. Instead of using

    document.body.appendChild( infoBox );
    , Add an id to your div like id="container". Then use the following:

    var parentContainer = document.getElementById('container');
    parentContainer.insertBefore(infoBox,parentContainer.firstChild);
    
  2. I'm not entirely certain about your infoBox.style.x, but you can try using infoBox.style.left = "0px;" and infoBox.style.top = "-200px" with positioning e.g. relative/absolute.

  3. If you opt for the second option, make sure to properly set the CSS style of your div. Especially this part:

    body { padding: 20%; background-color: #CCCCCC; }
    If my explanation is confusing, here's a sample code (jsfiddle) that may not be perfect, but it can serve as a starting point for customization based on your needs.

Answer №3

If you're looking for a simpler solution, I have a component that might help. It's not as comprehensive as a framework, but it's quite effective:

This component creates "panels" using HTML elements (existing or generated) and offers various methods to manipulate them. You can adjust position, size, opacity, simple animations, collision detection, bearing, etc. While it may have some limitations, it has proven useful in many cases.

One of the examples includes a basic "popup definitions" feature that can easily be customized to suit your requirements.

In essence, you create panels for popups and convert your click targets into panels (as demonstrated in the example with minimal code). Your onClick event handler could look something like this:

// Set the Popup panel to the same position as the clicked element.
PopPanel.setPosition(this.getPosition());
// Shift the position of the popup panel up 210 pixels
PopPanel.shiftPosition([-210, 0]);
// Show the panel
PopPanel.setDisplay("show");
// Fade the panel in (Animate opacity)
PopPanel.setOpacity(100, 0 , 200);

While you're on the right track already, the suggestions provided earlier should help resolve your current issue.

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

An issue arises when data from the parent ajax call is being referenced

I am encountering a situation where I have nested ajax functions within each other. $.ajax({ url: '../...', type: 'POST', dataType: 'JSON', ...

Discover the hexadecimal color code generated from an rgba color

Do you know of a service that can determine the final hexadecimal value of an rgba color? For instance, if my body background-color is set to #FF0000 and my header is positioned over it with a background-color of rgba(0,0,0,.7), how can I find out what the ...

Various style sheets are used for the production and staging environments

Is there a way to set up different styles for staging in node environments? Let's say I have the following scss files: scss/style.scss scss/theme.scss scss/green.scss After compiling, it gives me: style.scss Now, I'd like to change the style ...

Determining the height of a Bootstrap column in relation to another element

Utilizing the grid layout from bootstrap, I have the following structure: <div id="prof_cont_enclose"> <div class="row"> <div class="prof_cont_row"> <div class="col-xs-12 col-sm-4 col-md-2 col-lg-2 prof_elem"&g ...

What steps can be taken to have Eslint/Prettier report errors and warnings within a CI environment?

Recently, I encountered an issue with my Vue app where I am using Eslint with Prettier. Even though I have set up a Github action to check the code style, running npm run lint -- --no-fix only logs the warnings and does not cause the workflow to fail. I r ...

Find all relevant employee information at once without the need for iteration

I have structured two JSON arrays for employee personal and company details. By inputting a value in the field, I compare both tables and present the corresponding employees' personal and company information in a unified table. <html> ...

Troubleshooting problems with dates in jQuery AJAX

Hey, I recently worked on formatting dates in jQuery Ajax. After fetching a date value from the database, I converted it to the format dd-MM-YYYY. However, there seems to be an issue where I'm receiving the previous month. For example, if the database ...

Searching for repeated values across disparate object fields?

Inquiring about the method to utilize mongoose for identifying duplicate values across different fields. Providing a sample document for reference: { "followers": { { "_id": "5bf6d610d3a3f31a6c75a9f4" }, ...

Unique lightbox effect with multiple layers

Currently, I am working on implementing a lightbox effect to showcase images to the user using a GridView. Upon clicking an image, a new layer should appear above the current page displaying a larger version of the image along with some description. Althou ...

Adjusting the size of images to seamlessly fit within a card in Bootstrap 5 without changing the dimensions of the card

I am facing an issue with a Bootstrap 5 card split into 2 columns. First Column Second column Image1 Text Image2 Text The challenge arises because not all images are the same size, impacting the overall card size. I recently discovered a soluti ...

Aria attribute fails to display placeholder text

In my search feature, I have implemented functionality that announces the number of results found for every toggle with the screen reader NVDA. For example, pressing 'a' might say there are 20 results, while pressing 'ag' might say ther ...

Submitting a form with Multer when the user chooses to upload a file or not

I have integrated multer into my express app for handling form submissions. The issue I am facing is with the optional image upload feature in the form. Users have the choice to add a photo if they want, but they should also be able to submit the form wi ...

AngularJS mdDialog not supporting Tinymce functionality

I'm attempting to integrate the TinyMCE editor into an AngularJS mdDialog. Working Plunker: http://embed.plnkr.co/s3NsemdcDAtG7AoQRvLh/ Plunker with issues: http://embed.plnkr.co/fL8kGLl3b4TNdxW1AtKG/ All features are working fine except for the d ...

Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it. I have an HTML table with images used as buttons: <td> <button class="trigger"> <img src="D:\Elly Research\ CO2858\Presentation\Calypso ...

Locate a specific tag within an XML document using user input and then showcase the content that is encapsulated by it utilizing Node

Could someone kindly advise on how to locate a tag name within an XML dom based on user input and then iterate through and display all content within it? For example, if the user enters 'unit', the program should display everything within the uni ...

Issue with Angular ngModel not syncing with variable changes

Currently using Angular 4 and Typescript, I have a table containing <select> elements in my template: <tr *ngFor="let task of tasksDetails"> <td>{{task.name}}</td> <td> <select class="form-control" [(ngMode ...

Configuration of Bootstrap "col" without an xl number

Hello everyone, I am currently working on a project using Bootstrap, where I have a row with five child elements: <div class="container"> <div class="row"> <div class="col">[content]</div> ...

Is there a way to adjust the title length so that it can change dynamically?

https://i.sstatic.net/Tu9QM.pngCurrently, the title has a fixed background color which may widen if the resolution is smaller than the original size. My aim is to create a dynamic background color that adjusts based on the resolution. Regardless of wheth ...

Discovering the page load times of web elements on a website with the help of Selenium WebDriver

On my HTML5 webpage, there are 4 charts that each take a different amount of time to load after the static content has already loaded. The loading process is indicated by a 'rendering' circle image for all 4 charts. I am looking for a way to dete ...

What is the method for aligning text to the right side within a ListItem?

Currently, I have these elements where the "YoYo" text is aligned to the left by default. However, I am looking to adjust the positioning of some "YoYo" texts so that they can appear on the right side. I attempted to provide a style object with justifyCon ...