Creating a JavaScript popup script from scratch

I'm looking to create a script using only JavaScript that will display a popup when the page loads.
The background should be faded and I want to include custom content in the popup. I don't want to utilize CSS or HTML directly.
Embed the CSS and HTML within the JavaScript code. Is there anyone who can assist me with this project?
I am comfortable handling the styling aspect on my own.
I am limited to creating a popup with external CSS and HTML, not just pure JS. The popup needs to be simple and appear when the page loads.

Your help would be greatly appreciated!!

Preferably, I'd like to use JSFiddle for this task.

Answer №1

Here is an updated solution:

To show or hide a popup using CSS, you can simply utilize the display style property and toggle it on button onClick event.

Updates:

  • Add a placeholder element for the popup in the DOM

  • Apply CSS styles for the popup - refer to the provided CSS in the answer

  • Inject the popup into the DOM dynamically using the innerHTML property of JavaScript and include the necessary JS functions for showing/hiding the popup

This is an example implementation:

document.body.onload = addElement;

function addElement () { 
  var newDiv = document.createElement("div"); 
  newDiv.innerHTML += '<button class="open_button" onClick="openPopup()">Open Popup</button><div id="popup" style="position: absolute;width: 300px;z-index: 999;display: none;top:0;background-color: #fff;border: 1px solid #ddd;border-radius: 5px;box-shadow: 0 2px 8px #aaa;overflow: hidden;padding: 10px;"><div class="popup_body" style="height: 100px;">This is a sample popup</div><button class="close_button" onClick="closePopup()">Close</button</div>';

  var currentDiv = document.getElementById("main_container"); 
  document.body.insertBefore(newDiv, currentDiv); 

  openPopup();
}

function openPopup() {
  var el = document.getElementById('popup');
  el.style.display = 'block';
  
  document.body.style.background = '#353333'; // Update: set window background color to black
}

function closePopup() {
  var el = document.getElementById('popup');
  el.style.display = 'none';
  document.body.style.background = 'white';
}

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

Meteor is failing to update the data in MongoDB

I have encountered an issue with the following code snippet: Nodes = new Meteor.Collection("nodes"); [...] Template.list.events({ 'click .toggle': function () { Session.set("selected_machine", this._id); Nodes.update(Session.get("s ...

JavaScript allows you to create matrices from squares

Hey everyone, I'm facing an issue with creating matrices in HTML. I need to display a 5x5 matrix where each index is represented by a square. I tried using a span template for the box and then wrote a script to populate the matrices, but it's no ...

Arranging components in a horizontal layout on Jquery mobile

I'm completely new to Jquery mobile and I'm having trouble getting these elements aligned. Here's my code, but I need the two icons to line up horizontally with the caption "Heading". <h3>Heading</h3> <img src="../re ...

encasing a container element around every trio of elements

I'm currently working on grouping every 3 divs with a class of search-audio inside a div with a class of slide. The issue I'm facing is that it's giving me an error stating that elem.parentElement is undefined... However, the initial part ...

How can I monitor and handle JavaScript errors without causing TestCafe tests to fail?

As I begin writing TestCafe tests, a problem arose on our website - a JS error in the console causing test failures. While it was satisfying to catch this issue, it also highlighted the fact that even minor JS errors could lead to test failures and hinder ...

Error encountered in NextJS middleware: NetworkError occurred while trying to retrieve resource

I'm currently working with a middleware setup in NextJS based on an old tutorial. The code provided in the tutorial seems to be functioning correctly, but when I implement the same code, I encounter a NetworkError. Upon further investigation, it appea ...

How do I specify filter selectors for events passed as an object in JQuery's on() method?

I've been pondering about the second syntax of JQuery's on() method where events are passed as an object: services.on({ 'mouseenter': function(e){ console.log('enter', e.target); }, 'mouseleave': function ...

Design for implementing "new" functionality in JavaScript

I recently delved into the world of JavaScript Patterns through Stoyan Stefanov's book. One pattern that caught my attention involves enforcing the use of the new operator for constructor functions, demonstrated with the following code snippet: funct ...

Discover the combobox element and its value can be easily achieved by using Selenium's find_element_by_xpath method

I am having trouble setting a value in a combobox using selenium. The find_element_by_xpath statement is failing to locate the combobox by class or ng-model. Specifically, I am attempting to change the time period for a stock from one day to one week. Her ...

Terminate the JWT token and automatically log out the user in the event of a banning or modification

Greetings fellow developers, I've been working on enhancing my application's user system to include functionality for administrators to upgrade an account's level (granting admin privileges if it reaches level 10) or ban users from the site ...

"Data is not defined" error message is triggered when using jQuery DataTable Row Details

While utilizing jQuery Data Tables to construct a datatable with row details, I encountered an error in jquerydatatables.js: data is undefined The JavaScript code being used is: $(document).ready(function() { var dt = $('#tbl_cheque_history' ...

Double-checked in p:commandButton, encountering a race condition with oncomplete

When I execute the server action using p:commandButton, I then refresh the form to display hidden fields and show a dialog. Attempting to refresh only the panels with hidden buttons yields the same result: After I call dialog.show(), a second refresh is t ...

Ensuring each field is filled correctly in a step-by-step registration form

I have been working on implementing a step-by-step registration form, and I am facing an issue. When I click on the next button, all fields should be mandatory to proceed to the next step. It's crucial for the user experience that they fill out all th ...

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

How to deactivate the dropdown hover effect in ngx-intl-tel-input

Issue: When hovering over the dropdown items in the country list, I'm encountering a gray background color that I'd like to remove while still maintaining the functionality of the dropdown. Despite attempting to set background-color: transparent ...

When it comes to JavaScript, it considers the number 0 as equivalent

I am facing an issue with my spring endpoint that is returning an Enum named StatoPagamentoEnum: Java enum definition @JsonFormat(shape = JsonFormat.Shape.ARRAY) public enum StatoPagamentoEnum { DA_PAGARE(0), PARZIALMENTE_PAGATA(1), PAGATA(2 ...

Enter information into the TextArea and jQuery dialog

I require assistance in populating a textarea with data obtained from querying a database. I have a jQuery dialog that contains another dialog, inside of which is a textarea. Here is some pseudocode: <MODAL> <modalB> <TextArea>s ...

navigating a collection of objects and retrieving individual property values

I am having trouble extracting values from an array of objects, specifically only the values from the first object in each sub-array. Here is how my array of objects looks: items [ [ {id: 1, title: "title1", imgUrl: "https://someimage1"}, {id: 2 ...

What can be done to stop the caching of the route that router.push() redirects to in Next.js middleware?

Encountering an issue with client-side navigation and middleware in the router. It seems that the router is storing the initial redirect path and subsequent navigations bypass the middleware. This behavior ceases upon browser refresh and does not occur in ...

Encountering a "Text creation error" while trying to run a three.js demo on Microsoft Edge using the WebGL context

When attempting to run three.js on Edge, an error message appears stating 'text could not be created. Reason: Could not create a WebGL context.' Even after trying to execute the official three.js example on Edge, the same error persisted, while ...