How can I show a pop-up notification on my webpage next to a specific link

Greetings! Currently, my code triggers an alert when I click on the "send an alert" link.

However, the alert pops up far from the actual link itself.

I am aiming to have the alert display close to the link that triggers it.

What adjustments should I make in my code to ensure the alert is positioned next to my link?

Link to the code snippet

<alert>
  <div id="overlay" ></div>
  <div id="alertPanel" ></div>
</alert>

<a href="#" onclick="alert('Custom Alert','content of this alert');">send an alert</a>
<br>
<a href="#" onclick="alert('Custom Alert number 2','content of this second alert');">send an alert</a>
alert #overlay{
  position:fixed;
  z-index:999;
  top:0px;
  left:0px;
  width:100%;
  height:100%;
  background-color:#000;
  opacity:0.7;
  display: none;
}
alert #alertPanel{
  position:absolute;
  top:25%;
  min-height: 170px;
  width: 450px;
  margin-left: 24%;
  z-index:9999;
  color:#000;
  border:1px solid #303030;
  background-color:#eaeaea;
  display: none;
  text-align: center;
  font-size: 24px;
  font-weight:100%;
  margin-bottom: 20px;
}
alert div.texte{
  width: 400px;
  display:inline-block;
  padding:20px 0px 10px 0px;
  word-wrap: break-word;
}
alert span.close{
  background: url('') no-repeat center center;
  cursor:pointer;
  height:32px;
  width:32px;
  position:absolute;
  right:12px;
  top:12px;
  cursor:pointer;
  -moz-border-radius:5px;
  -webkit-border-radius:5px;
  border-radius:5px;
  opacity:1.0;
}

alert #alertPanel h2{
  font-weight:100%;
  font-size:22px;
  padding:25px 0px 15px 15px;
  text-align:center;
  text-shadow:1px 1px 1px #000;
  margin:0px;
  background-color: #323232;
  border:2px solid #fff;
  -moz-box-shadow:0px 0px 8px #000;
  -webkit-box-shadow:0px 0px 8px #000;
  box-shadow:0px 0px 8px #000;
  color: #FFFFFF;
}
window.alert = function(title, message) {
    document.getElementById("alertPanel").innerHTML = "<span class=\"close\" onclick=\"closeAlert();\"></span><h2>" + title + "</h2><div class=\"texte\">" + message + "</div>";
    document.getElementById('alertPanel').style.display='block';
    document.getElementById('overlay').style.display='block';
}
function closeAlert()
{
    document.getElementById('alertPanel').style.display='none';
    document.getElementById('overlay').style.display='none';
}

Answer №1

Make sure to pass the clicked element as an argument in the onclick handler.

Then, utilize the element to determine its position using getBoundingClientRect and apply it to the alertPanel.

window.alert = function(link, title, message) {
  
  // Save this query result in a variable for efficiency
  let alertPanel = document.getElementById("alertPanel")
  alertPanel.innerHTML = "<span class=\"close\" onclick=\"closeAlert();\"></span><h2>" + title + "</h2><div class=\"texte\">" + message + "</div>";
  alertPanel.style.display = 'block';
  
  // Get the position of the clicked link
  let position = link.getBoundingClientRect()
  
  // Apply the position to the alertPanel
  alertPanel.style.top = position.top + 20 + "px";
  alertPanel.style.left = position.left + "px";
  
  document.getElementById('overlay').style.display = 'block';
}

function closeAlert() {
  document.getElementById('alertPanel').style.display = 'none';
  document.getElementById('overlay').style.display = 'none';
}
body{
  font-family:'Open Sans',sans-serif;
  background-color: #DEDEDE;
}
alert #overlay{
  position:fixed;
  z-index:999;
  top:0px;
  left:0px;
  width:100%;
  height:100%;
  background-color:#000;
  opacity:0.7;
  display: none;
}
alert #alertPanel{
  position:absolute;
  top:25%;
  min-height: 170px;
  width: 450px;
  /*margin-left: 24%;*/
  z-index:9999;
  color:#000;
  border:1px solid #303030;
  background-color:#eaeaea;
  display: none;
  text-align: center;
  font-size: 24px;
  font-weight:100%;
  /*margin-bottom: 20px;*/
}
alert div.texte{
  width: 400px;
  display:inline-block;
  padding:20px 0px 10px 0px;
  word-wrap: break-word;
}
alert span.close{
  background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAANjr9RwUqgAAACBjSFJNAABtmAAAc44AAPJxAACDbAAAg7sAANTIAAAx7AAAGbyeiMU/AAAG7ElEQVR42mJkwA8YoZjBwcGB6fPnz4w/fvxg/PnzJ2N6ejoLFxcX47Rp036B5Dk4OP7z8vL+P3DgwD+o3v9QjBUABBALHguZoJhZXV...
...
<a href="#" onclick="alert(this,'Custom Alert','content of this alert');">send an alert</a>
<br>
<a href="#" onclick="alert(this,'Custom Alert Number 2','content of this alert number 2');">send an alert</a>

Answer №2

Make sure to adjust the position of your alert element by setting it to position: relative, and align the placement of the alertPanel accordingly.

Answer №3

You can customize the position in this class: alert #alertPanel

For instance, I adjusted the top and margin-left properties as follows:

  top: 10px;
  margin-left: 300px;

window.alert = function(title, message) {
    document.getElementById("alertPanel").innerHTML = "<span class=\"close\" onclick=\"closealert();\"></span><h2>" + title + "</h2><div class=\"text\">" + message + "</div>";
    document.getElementById('alertPanel').style.display='block';
    document.getElementById('overlay').style.display='block';
}
function closealert()
{
    document.getElementById('alertPanel').style.display='none';
    document.getElementById('overlay').style.display='none';
}
body{
  font-family:'Open Sans',sans-serif;
  background-color: #DEDEDE;
}
alert #overlay{
  position:fixed;
  z-index:999;
  top:0px;
  left:0px;
  width:100%;
  height:100%;
  background-color:#000;
  opacity:0.7;
  display: none;
}
alert #alertPanel{
  position:absolute;
  top: 10px;
  min-height: 170px;
  width: 450px;
  margin-left: 250px;,
  z-index:9999;
  color:#000;
  border:1px solid #303030;
  background-color:#eaeaea;
  display: none;
  text-align: center;
  font-size: 24px;
  font-weight:100%;
  margin-bottom: 20px;
}
alert div.text{
  width: 400px;
  display:inline-block;
  padding:20px 0px 10px 0px;
  word-wrap: break-word;
}
alert span.close{
  background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAABGdBTUEAANjr9RwUqgAAACBjSFJNAABtmAAAc44AAPJxAACDbAAAg7sAANTIAAAx7AAAGbyeiMU/AAAG7ElEQVR42mJkwA8YoZjBwcGB6fPnz4w/fvxg/PnzJ2N6ejoLFxcX47Rp036B5Dk4OP7z8vL+P3DgwD+o3v9QjBUABBALHguZoJhZXV2dVUNDgxNIcwEtZnn27Nl/ZmZmQRYWFmag5c90dHQY5OXl/z98+PDn1atXv79+/foPUN9...
...
<alert>
  <div id="overlay"></div>
  <div id="alertPanel"></div>
</alert>

<a href="#" onclick="alert('Custom Alert','content of this alert');">Send an alert</a>
<br>
<a href="#" onclick="alert('Custom Alert number 2','content of this alert number 2');">Send another one</a>

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

The server encountered an issue: 415 Unsupported Media Type. JSON data was not loaded as the Content-Type in the request was not 'application/json'

I'm currently working on a React-Python(Flask) project and encountering an error in the backend: '415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not 'application/json'. the frontend ...

Tips for sending a script argument using run-s to a pre-script task in NodeJS

I am facing an issue with running a script before the actual build script in my multi-module Angular project. The script is responsible for copying some files, so initially I thought of placing it under the prebuild script. However, it seems like this appr ...

Trigger an event in Vue with specified parameters

I am attempting to emit a function with parameters in the following way. template: ` <div class="searchDropDown"> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup=" ...

Executing Java method via JavaScript by simply clicking a button

I am currently facing a challenge in finding a way to invoke a Java method from JavaScript and pass user input variables into the method call. The main issue I have encountered is that JavaScript seems to interpret/resolve the Java method during page load. ...

Obtain an Observable by subscribing with RxJS

My current situation involves a service that makes an HTTP request to an API in order to fetch data. I have some specific logic that needs to be implemented on the observable within the service, while still allowing for subscription to the Observable in my ...

How can I successfully transfer information from a JQuery Ajax request to an ASP.NET webpage?

Utilizing JQuery Ajax to transmit data from a different domain to an ASP.NET page in another domain poses a challenge. The response can be obtained back from the ASP.NET page, but sending the data through JQuery Ajax is proving difficult. Here's the c ...

Using an id as the attribute value for a React ref

I have a question about referencing DOM nodes in a component. Currently, I am able to get the nodes and children using the following code: export class AutoScrollTarget extends React.Component { constructor(props) { super(props); this ...

Is there a way to adjust the border color of my <select> element without disrupting the existing bootstrap CSS styling?

In my Bootstrap (v4.5.3) form, the select options appear differently in Firefox as shown in the image below: https://i.sstatic.net/3suke.png Upon form submission, I have JavaScript code for validation which checks if an option other than "-- Select an Op ...

Using Jest spyon is effective when mocking a module required with 'require', but it does not work when the module is imported using 'import'

Testing the functionality of my third-party library (iframe-resizer) by verifying if a specific function is called during a test. import React from 'react'; import { fireEvent, render } from 'react-testing-library'; let depModule = req ...

Tips for selectively executing a script based on whether the DIV is within the viewport

I have a created a script as shown below: jQuery(function($) { $('.count').countTo({ from: 0, to: '400', speed: '3000', refreshInterval: 50, onComplete: func ...

Halt execution of routes using backbone.js

Is it feasible to halt route execution within backbone.js solely using the router? I understand there is a callback function for each route where I could verify if routing is permitted, but I am unsure how to prevent execution based on a property (such as ...

Qt offers a powerful feature that allows the seamless exposure of any C++ object to Javascript

I am interested in making a C++ object accessible from my class to Javascript. Let me provide an example to better explain what I intend to do. In a specific project, I am working on creating a simple ShopApp. So how can I achieve something like this (wh ...

Switching CSS styles - seeking a smoother integration

I have successfully implemented a JS CSS switcher, which works brilliantly. However, I would like it to function more seamlessly. When opening a new page on the site, the default CSS style sometimes flickers briefly before the selected CSS style is reappli ...

What is causing compatibility issues between html5lightbox and angular?

After integrating angular.js into my project, I encountered an issue with html5lightbox not working as expected. Instead of opening images and PDF files in a lightbox, clicking on a link takes me to another page. var app = angular.module('MyApp&apos ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...

What steps can be taken to ensure that typescript exports remain backward compatible with module.exports?

I initially defined a node.js module in the following way: function sayHello(){ // do something } module.exports = sayHello; After transitioning to typescript, I created sayHello.ts like this: function sayHello():void { // do something } export de ...

The $_POST value is consistently the final entry within my <tr> element

I'm facing a challenge that has me stuck. I have a basic webpage where I display a table of all Users queried from a database. The idea is that when a user clicks on a table row, they should be redirected to another page where they can edit the select ...

Activate or deactivate Reactstrap tooltip depending on the button's current state

I've chosen to use Reactstrap (version 6.5.0) for the styling of my ReactJs project. Within my inline form, I have a submit button that remains disabled until the user has input all mandatory details. The goal here is twofold: Show the user a tool ...

Having trouble accessing information from Firebase Realtime Database within a React Native application

I am currently developing a React Native application that interacts with a Firebase database for reading and writing data. I have configured my Firebase permissions to allow read and write access: { "rules": { ".read": true, ...

Navigate between pictures using hover in jQuery

I am working on creating a feature where images cycle through individually every 2 seconds, but switch to the right image when its associated link is hovered. So far, I have managed to make the images show up on hover, but I am struggling with getting them ...