Guide on creating a toggle effect for a div with querySelector and addEventListener

I utilized the email and password divs provided by Bootstrap. The CSS for the id dropdownlogin includes display: none; in this post, I hope that I have shared adequate information.


<script>
    document.addEventListener('DOMContentLoaded', function()
    {
        document.querySelector("#dropdownlogin").addEventListener('click', function()
        {
            dropdownlogin.style.display = block;
        })
    });
</script>

<div class="login">
    <a href="#">Login</a>
    <center>
        <form id="dropdownlogin" action="">
            <div class="form-floating mb-3">
                <input type="email" class="form-control" id="floatingInput" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c020d01092c09140d011c0009420f0301">[email protected]</a>">
                <label for="floatingInput">Email address</label>
            </div>
            <div class="form-floating">
                <input type="password" class="form-control" id="floatingPassword" placeholder="Password">
                <label for="floatingPassword">Password</label>
            </div>
            <div id="loginbtn">
                <button>Login</button>
                <button>Forgot Password</button></p>
            </div>
        </form>
    </center>
</div>

Answer №1

To enable showing or hiding a form upon clicking the Login link, you can attach an event to the Login and toggle the visibility of the form by adding a class to it. Below is a sample JavaScript code snippet for this functionality:

const formContainer = document.getElementById('dropdownlogin');

function toggleForm(e) {
  formContainer.classList.toggle('hideForm');
}
.hideForm {
  display: none
}
<div class="login">
  <a href="#" onClick="toggleForm()">Login</a>

  <form id="dropdownlogin" class="hideForm" action="">

    <div class="form-floating mb-3">
      <input type="email" class="form-control" id="floatingInput" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1779767a7257726f767a677b723974787a">[email protected]</a>">
      <label for="floatingInput">Email address</label>
    </div>
    <div class="form-floating">
      <input type="password" class="form-control" id="floatingPassword" placeholder="Password">
      <label for="floatingPassword">Password</label>
    </div>
    <div id="loginbtn">
      <button>Login</button>
      <button>Forgot Password</button>
    </div>
  </form>

</div>

Answer №2

<script>
 var displayLogin = document.querySelector("#dropdownlogin")
 var buttonClick = document.querySelector("#mybtn")

 buttonClick.addEventListener("click", function () 
    {
       displayLogin.classList.toggle("hidden")
    });
</script>

.hidden{
display:none;
}

<div class="login">
    <a href="#">Login</a>
    <center>
        <form id="dropdownlogin" class="hidden" action="">
            <div class="form-floating mb-3">
                <input type="email" class="form-control" id="floatingInput" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e48a858981a4819c8589948881ca878b89">[email protected]</a>">
                <label for="floatingInput">Email address</label>
            </div>
            <div class="form-floating">
                <input type="password" class="form-control" id="floatingPassword" placeholder="Password">
                <label for="floatingPassword">Password</label>
            </div>
            <div id="loginbtn">
                <button>Login</button>
                <button>Forgot Password</button></p>
            </div>
        </form>
        <button id="mybtn">Click Me!</button>
    </center>
</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

Rails javascript not triggering even after the page is loaded with `page:load`

My experience with using Stripe in Rails has been smooth, except for some issues with Ajax calls not working properly after page refresh. I suspect this might be related to Turbolinks as the 'ready page:load' event doesn't behave as expected ...

Bootstrap glyphicon not in sync with input field alignment

Having an issue with aligning the upper border of a search input field when using Angular with Bootstrap and adding a glyphicon next to it. div.input-group(ng-show='feeds.length > 0') span.input-group-addon.glyphicon.glyphicon-search in ...

Maximizing JavaScript efficiency: Returning a value within an if statement in an AJAX call

In my function, I have a condition that checks the idType. If it is 1, an ajax call is made to a php file to retrieve the name associated with the specific idName and return it. Otherwise, another example value is returned. function obtainName(idName, idTy ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

Is there a way to center the text at 0% using text-align in Bootstrap?

My progress bar, designed with Bootstrap, currently displays the text in a way that is not centered as desired. The issue I am experiencing is that the "0/0" text shifts to the left and using text-align: center; does not seem to resolve this alignment pro ...

Having trouble debugging a website remotely? Dealing with a JSON problem specifically in IE8

Currently, the website is functioning flawlessly on various machines except for those used by the client in Africa. Unfortunately, I have no way of accessing his specific machine due to geographical constraints. The client has limited IT knowledge, and we ...

Custom component not rendering expected CSS style

I have successfully developed a custom web component without using any framework. I then proceeded to populate it with content from a template tag. Although I was able to manipulate the content using JavaScript, I encountered difficulties when trying to m ...

Javascript leaping across intervals

I'm currently working on creating a unique JavaScript slideshow with a customized pause interval for each slide. Let's say I have a slideshow with 3 slides and I want the pause intervals to be as follows: 30 seconds 8 sec 8 sec |---- ...

Personalizing the look of Stripe Payment Component in a React Application

Currently, I have integrated the Stripe Payment Element into my React application using the code snippet below: import { useStripe, useElements, PaymentElement, } from '@stripe/react-stripe-js' export const PaymentDetails = () => { const st ...

Clicking on links will open them in a separate tab, ensuring that only the new tab

Is there a way to open a new tab or popup window, and have it update the existing tab or window whenever the original source link is clicked again? The current behavior of continuously opening new tabs isn't what I was hoping for. ...

What exactly comprises an HTTP Parameter Pollution attack within the context of Node.js and Express.js?

I came across this information on https://www.npmjs.com/package/hpp According to the source, "Express populates http request parameters with the same name in an array. An attacker can manipulate request parameters to exploit this vulnerability." I am cur ...

What is the best way to set the input type file to null when deleting an image in Vue?

My form allows users to upload an image, and everything was functioning properly until I encountered an issue. When I remove an image and try to upload the same image again, the @change function is not triggered. I am unable to reset the file value to null ...

IE8 does not show AJAX response right away

I have encountered a peculiar problem with the code below. In Internet Explorer 8, the content retrieved through xmlHttpRequest does not appear immediately after clicking the link. It only displays after moving the mouse or cursor following the click. < ...

Tips for creating an HTML report using Python

Currently, I am searching for a solution to convert my saved matplotlib graphs as png files along with some data frames into HTML format. This is similar to how I typically use R2HTML in R. Despite my efforts, I have not been able to locate clear informat ...

Is it secure to store the access token within the NextAuth session?

Utilizing a custom API built with Node.js and Express.js, I have implemented nextAuth to authenticate users in my Next.js application. Upon a successful login, the date is stored in the nextAuth session and can be accessed using the useSession hook. To acc ...

Is there a way to troubleshoot a webpack-compiled npm module effectively?

Looking to debug an npm module compiled with webpack by setting breakpoints and stepping through the code? The issue may arise when importing the module locally using npm link, as only the compiled code is accessible for debugging from the application. W ...

Creating dynamic dropdown menus within a Rails 3 form using Prototype and incorporating database queries

Recently, I've been on the hunt for a seamless method to create dynamic dropdown menus within a form that can be populated with data from a database based on the selection of a previous dropdown. Unfortunately, my search for a suitable Rails 3/prototy ...

Kendo checkbox toggle issue with switching between true and false states is not functioning correctly

How can I make a button appear when one or more checkboxes are clicked? Currently, the toggle function only activates when I select one checkbox, and then deactivates upon selecting another. Any guidance on improving this functionality would be greatly app ...

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

Encountering an issue with my Discord bot where it displays the error message "Unable to access property 'cache' of an undefined object"

I encountered an issue while setting up discord-xp for my bot. Whenever I attempted to use the leaderboard command, an error message popped up: username: client.users.cache.get(key.userID) ? client.users.cache.get(key.userID).username : "Unknown" ...