Creating a modal popup when a button is clicked

After searching online for a way to make my sign up modal pop up when the signup button in my navbar is pressed, I was unable to find any information on how to achieve this. I suspect it involves JavaScript, but my knowledge of JS is limited.

I attempted to experiment with some JS code that could trigger the modal to appear, but it only resulted in translation, which didn't look good. My goal is to have the modal show up in the center of the user's screen and restrict scrolling between the top and bottom of the modal if the user's screen is small. If the screen is large enough to display the entire modal, I don't want the user to be able to scroll until they either close the signup modal or continue with the signup process. I have provided an image of the modal, along with the HTML and CSS code. Additionally, I prefer the background not to be interactive while the modal is open.

Check out the image of my sign-up modal here.

<div class="modal modal-sheet position-static d-block bg-body-secondary p-4 py-md-5 signup-modal" tabindex="-1" role="dialog" id="modalSignin">
    <h2>Register your Account</h2>
  
  <div class="modal-body p-5 pt-0">
    <form class="">
      <div class="form-floating mb-3">
        <input type="text" class="form-control rounded-3 cbs-form input-group-custom-field" id="usernameInput" placeholder="Username" autocomplete="on" required>
        <label for="usernameInput">Username</label>
      </div>
      
      <!-- Additional form inputs omitted for brevity -->

    </form>
  </div>
</div>

.signup-modal-background { background-color: #222022; }

Update: Success! Thanks to everyone who assisted me. For those facing a similar issue, I've shared the code that worked for me:

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Launch demo modal</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Answer №1

Your query seems to be related to the functionality of the native bootstrap modal. To address it:

If you have a modal with the ID #modalSignin, you can trigger it using a signup button like this:

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalSignin"> ... </button>

Alternatively, if you are unable to use the data-bs-target attribute, you can set up an event listener like so:

$('#your-signup-button-id').on('click', function() {
    var modalToggle = new bootstrap.Modal(document.getElementById('the-modal-id'))
    modalToggle.show()
});

You can also achieve this using vanilla JavaScript:

document.getElementById('your-signup-button-id').addEventListener('click', function() { 
    var modalToggle = new bootstrap.Modal(document.getElementById('the-modal-id'))
    modalToggle.show()
});

This should work smoothly unless there are conflicting CSS rules that affect the default behavior (such as allowing scrolling on the main content).

For more details, refer to: Bootstrap 5 modal

Answer №2

Check out this snippet of code

<script>
var popup = document.getElementById('popupBox');
var button = document.getElementById("openPopupButton");
 button.onclick = function() {
    popup.style.display = "block";
    document.body.style.overflow = "hidden"; // Disable scrolling in the background
  }

window.onclick = function(event) {
    if (event.target == popup) {
      popup.style.display = "none";
      document.body.style.overflow = ""; // Enable scrolling in the background
    }
  }
</script>

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 addition of input fields on keyup creates problems in the initial field of each row

I am currently working with a table and attempting to calculate the sums as follows: td(1) + td(2) + td(3) = td(4), td(5) + td(6) + td(7) = td(8), td(9) + td(10) + td(11) = td(12). This is the code I have implemented: $(document).ready(function () { ...

What is causing my Javascript media query for the sidebar to not function properly?

I am working on implementing a sidebar that slides out 250px using JavaScript on the desktop view. However, I want the sidebar to take up 100% width when viewed on mobile devices. Despite my attempts to use Media Queries in JavaScript to achieve this, I am ...

Issue with nth-child selector not functioning as expected in unordered list

I have a straightforward <nav> setup with an unordered list inside: nav { position: absolute; right: 0px; white-space: nowrap; } nav ul { padding: 0; margin: 0; } nav ul li { clear: both; white-space: nowrap; color: white; displa ...

I successfully corrected the selectable options list in HTML/CSS and am now working on linking it to a Django char field. I'm currently facing some difficulties in figuring out

Below is a Django form field I have defined: source_currency = forms.CharField(max_length=5) Here is an example of Select/Option HTML: <select name="fancySelect" for="{{ form.source_currency.id_for_label }}" class="makeMeFancy" id="drop1"> ...

Components in Angular modules that are loaded lazily with identical names

I have developed an Angular application with multiple lazy-loaded modules. Each of these modules contains different components that are conceptually similar but vary in content. For example, each module may have its own "home" component. Is it advisable t ...

What is the most efficient way to transfer a large volume of documents from mongoDB using http?

I'm dealing with a large mongoDB database that contains millions of documents and I need to fetch them all at once without crashing or encountering cursor errors. My goal is to send this data over http using express in nodeJS. The collection contains ...

Guide to Spidermonkey Bytecode Documentation

I've been searching for a comprehensive guide to spidermonkey's bytecodes for some time now, or at least something that gives me an overview of their purpose. Does anyone know of a good resource for this? Thank you! ...

Is there a way to adjust the font size of a select option?

Looking to customize the appearance of a select option dropdown list. Wondering if it's possible to change the font sizes of individual options rather than keeping them all the same? For instance, having the default: -- Select Country -- displayed a ...

Numerous anchor links are present

Is it possible to eliminate the red lines between "google links" while keeping the border color as red? How can I achieve this? Here is the code snippet provided: <!doctype html> <html> <head> <title>Website</title> </he ...

Is it necessary to utilize process.env in node.js?

In my project, there is a .env file containing the following: ABC='abc' While in my app.js I can access the value abc using process.env.ABC, how can I require it to be used in my models' files? Attempting to use process.env.ABC in my model ...

individual elements displayed sequentially within the same block with variable naming

My code caters to both mobile and desktop versions, with the same elements in the FORM. However, only one block of code is visible at a time depending on the screen size, with one set to display: none. <div id="desktop"> <div id="content"> ...

What could be causing the DIV elements to not align side by side?

<div id="dvFirst" class="mainSecond" style="background: #6FA5FD;"> <div id="leftdiv3" class="leftdiv">Client: </div> <div id="rightdiv3" class="rightdiv"><asp:DropDownList ID="ddlCliNewMsg" AutoPostBack="t ...

Do we need to use the render method in ReactJs?

I'm curious about how ReactJs uses its Render() functionality. Let's say we have some HTML code within index.html: <section id="Hello"> <h1>Hello world</h1> <p>Something something Darkside</p> </section&g ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

Unable to receive a response in React-Native after sending a post request

My current challenge involves sending a response back after successfully making a post request in react-native. Unfortunately, the response is not arriving as expected. router.route("/addUser").post((req, res) => { let name= req.body.name; connection ...

Transmitting video through a local area network

I am seeking a solution to stream video content to a local network with potentially over 1000 viewers. The streaming will need to be accessible via web browsers such as Internet Explorer, Chrome, and Firefox, as not all users have internet access due to co ...

Incorporate personalized feedback into a datatable with server-side processing

Trying to implement server-side processing for a datatable loaded from an AJAX response using this specific example The server response being received is as follows: {"msg":null,"code":null,"status":null,"result":[{"aNumber":"3224193861","bNumber":"32159 ...

PHP code to display "ed elements that do not adjust height"

A php script is being utilized to scan a directory and populate a gallery with all the images. Within the <div id="content"> tag, the function <?php create_gallery("path"); ?> loads all the images. The issue arises when the height of the <d ...

I am encountering an issue with the Link tag from next/link that is throwing an error. The error message states: "React.Children.only expected to receive a single React element

Hey everyone, I've come across an issue with using next/link in my code. Every time I replace the anchor tag with the "Link" tag, I encounter an error. I've searched for a solution but haven't found one yet. Any help would be greatly appreci ...

JavaScript vs. markup: deciding between generating an extensive list of options or including them directly in

Recently, I encountered an issue with a .NET page that included a large number of identical dropdown lists within a repeater. Unfortunately, the rendering performance of the website was below expectations. In an attempt to improve the performance, I exper ...