The function is not being called as expected when using `onclick` or `eventListener('click')`

I'm in the process of developing a login form for my website that will offer 2 options - "login" and "signup". The concept is similar to mini tabs and iframe windows. Essentially, I have two divs side by side for "login" and "signup". When the user clicks on "login", I want a hidden div (currently set with height: 0 and overflow: hidden) to expand (height: auto; overflow: visible). It's important to note that "login" acts like a tab, not a submit button.

I'm facing an issue where the function is not being triggered as intended. Despite my troubleshooting efforts, even replacing it with a known working function did not yield any results.

I have shared all the code variations I attempted. In the HTML, I refrained from using both onClick within the tag simultaneously with addEventListener('click'). Similarly, in the JavaScript, I tried adding a class and setting the height separately.

My preference lies in utilizing event listeners combined with adding classes, which should enable the transition effect to function properly.

HTML:

         <div id="login-box">
         <span class="login-head">
           <h5 align="center" class="head">Login</h5><hr />
         </span>
         <ul class="drop-down">
         <li>

         <!-- LOGIN and SIGNUP tabs -->
          <div id="login-title" class="drop-down-head" onClick="loginExpand()">LOGIN</div>
          <div id="signup-title" class="drop-down-head" onClick="signupExpand()">SIGNUP</div>

          <!-- login content to be expanded from 0 height to auto when "login div" above is clicked -->
          <div id="login-content">
              <div class="input column" id="first-name">
                  <input placeholder="First Name" type="text" class="validate white">
                  <div id="first-name-tooltip" class="tooltip">First Name</div>
              </div>

CSS:

/* default state with 0 height, ideally with a .5s transition 0 height to auto */
#login-content, #signup-content {
  height: 0;
  transition: height .5s;
  -moz-transition: height .5s;
  -webkit-transition: height .5s;
  -o-transition: height .5s;
  overflow: hidden;
}

/* class to be added to div */
.expand {
  height: auto;
  overflow: visible;
}

/* link-like features to div */
.drop-down-head:hover {
  background: #8fffad;
  cursor: pointer;
}

Javascript:

document.addEventListener('DOMContentLoaded',function() {

  document.getElementById('login-title').addEventListener('click',loginExpand);
});

function loginExpand() {
  document.getElementById('login-content').style.height=500; //tried this
  document.getElementById('login-content').classList.add('expand'); //also tried this (separately, not together)
}

Answer №1

There seems to be an issue related to the CSS. The problem lies in assigning the overflow: visible; property with an id selector, which takes precedence over the class selector.

The .expand class won't be able to overwrite this property, resulting in the overflow remaining as hidden. You can try using the !important declaration in the CSS property to ensure it is applied by the browser.

To resolve this, one option is to add the visible property using javascript, or use the class selector in your CSS.

Sample Code using Javascript:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('login-title').addEventListener('click', loginExpand);
});

function loginExpand() {
    console.log("clicked");
    let elem = document.getElementById('login-content');
    elem.style.height = 500; //tried this
    elem.style.overflow = 'visible';
    elem.classList.add('expand'); //also tried this (separately, not together)
}
/* default state with 0 height, ideally with a .5s transition 0 height to auto */

#login-content,
#signup-content {
    height: 0;
    transition: height .5s;
    -moz-transition: height .5s;
    -webkit-transition: height .5s;
    -o-transition: height .5s;
    overflow: hidden;
}
/* class to be added to div */

.expand {
    height: auto;
    overflow: visible;
}
/* link-like features to div */

.drop-down-head:hover {
    background: #8fffad;
    cursor: pointer;
}
<div id="login-box">
    <span class="login-head">
        <h5 align="center" class="head">Login</h5><hr />
        </span>
    <ul class="drop-down">
        <li>
            <!-- LOGIN and SIGNUP tabs -->
            <div id="login-title" class="drop-down-head" onClick="loginExpand()">LOGIN</div>
            <div id="signup-title" class="drop-down-head" onClick="signupExpand()">SIGNUP</div>
            <!-- login content to be expanded from 0 height to auto when "login div" above is clicked -->
            <div id="login-content">
                <div class="input column" id="first-name">
                    <input placeholder="First Name" type="text" class="validate white">
                    <div id="first-name-tooltip" class="tooltip">First Name</div>
                </div>
        </li>
    </ul>
</div>

Sample Code using Class selector:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('login-title').addEventListener('click', loginExpand);
});

function loginExpand() {
    let elem = document.querySelector('.login-content');
    elem.classList.add('expand'); //also tried this (separately, not together)
}
/* default state with 0 height, ideally with a .5s transition 0 height to auto */

.login-content {
    height: 0;
    transition: all 3s;
    overflow: hidden;
}
/* class to be added to div */

.expand {
    height: 500px;
    overflow: visible;
    background-color: burlywood;
}
/* link-like features to div */

.drop-down-head:hover {
    background: #8fffad;
    cursor: pointer;
}
<div id="login-box">
<span class="login-head">
<h5 align="center" class="head">Login</h5><hr />
</span>
<ul class="drop-down">
    <li>
        <!-- LOGIN and SIGNUP tabs -->
        <div id="login-title" class="drop-down-head" onClick="loginExpand()">LOGIN</div>
        <div id="signup-title" class="drop-down-head" onClick="signupExpand()">SIGNUP</div>
        <!-- login content to be expanded from 0 height to auto when "login div" above is clicked -->
        <div class="login-content">
            <div class="input column" id="first-name">
                <input placeholder="First Name" type="text" class="validate white">
                <div id="first-name-tooltip" class="tooltip">First Name</div>
            </div>
    </li>
</ul>
</div>

Answer №2

If you want to try something different, consider using the display property instead of relying on overflow:

document.addEventListener('DOMContentLoaded', function() {
  
  document.getElementById('login-title').addEventListener('click', loginExpand);
});

function loginExpand() {
  document.getElementById('login-content').style.display = 'block';
}
#login-content,
#signup-content {
  height: 0;
  transition: height .5s;
  -moz-transition: height .5s;
  -webkit-transition: height .5s;
  -o-transition: height .5s;
}


/* add this class to div element */

.expand {
  height: auto;
  overflow: visible;
}


/* styles for link-like behavior in div */

.drop-down-head:hover {
  background: #8fffad;
  cursor: pointer;
}
<div id="login-box">
  <span class="login-head">
    <h5 align="center" class="head">Login</h5><hr />
  </span>
  <ul class="drop-down">
    <li>

      <!-- LOGIN and SIGNUP tabs -->
      <div id="login-title" class="drop-down-head" onClick="loginExpand()">LOGIN</div>
      <div id="signup-title" class="drop-down-head" onClick="signupExpand()">SIGNUP</div>

      <!-- expand the login content from 0 height to auto when "login div" above is clicked -->
      <div id="login-content" style=" display:none;">
        <div class="input column" id="first-name">
          <input placeholder="First Name" type="text" class="validate white">
          <div id="first-name-tooltip" class="tooltip">First Name</div>
        </div>

Answer №3

By simply adding !important to the .expand class in my CSS, everything is now working perfectly.

document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('login-title').addEventListener('click', loginExpand);
});

function loginExpand() {
  document.getElementById('login-content').classList.add('expand');
}
/* defining default state with 0 height and a 0.5s transition from 0 height to auto */

#login-content,
#signup-content {
  height: 0;
  transition: height .5s;
  -moz-transition: height .5s;
  -webkit-transition: height .5s;
  -o-transition: height .5s;
  overflow: hidden;
}


/* class added to expand div */

.expand {
  height: auto !important;
  overflow: visible !important;
}


/* hover properties for link-like features of the div */

.drop-down-head:hover {
  background: #8fffad;
  cursor: pointer;
}
<div id="login-box">
  <span class="login-head">
           <h5 align="center" class="head">Login</h5><hr />
         </span>
  <ul class="drop-down">
    <li>

      <!-- LOGIN and SIGNUP tabs -->
      <div id="login-title" class="drop-down-head" onClick="loginExpand()">LOGIN</div>
      <div id="signup-title" class="drop-down-head" onClick="signupExpand()">SIGNUP</div>

      <!-- click on "login div" above to expand login content from 0 height to auto -->
      <div id="login-content">
        <div class="input column" id="first-name">
          <input placeholder="First Name" type="text" class="validate white">
          <div id="first-name-tooltip" class="tooltip">First Name</div>
        </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

"Border-radius becomes less prominent on pointer interaction in Chrome and Safari due to WebKit's behavior

Having an issue with a list inside a div. The problem arises when there is a div containing a list, which limits the visibility of items for users. If the limit is exceeded, a scroll bar appears inside the div to allow users to see more items. Additionally ...

Adjust the height seamlessly on the homepage without the need for scrolling, while maintaining a stationary navigation bar and footer

Our latest project is designed specifically for mobile use. The fixed navigation bar is functioning perfectly. We also have a fixed footer with icons at the bottom. (All working well) The challenge we are facing is to make the content between the naviga ...

Leverage the power of React in tandem with Express

My web site is being created using the Express framework on NodeJS (hosted on Heroku) and I'm utilizing the React framework to build my components. In my project, I have multiple HTML files containing div elements along with React components that can ...

Jade, res.render, and res.write are essential tools for rendering

I am currently working on creating a simple FTP client in Node.js. Everything seems to be running smoothly, but I am facing difficulty in displaying the "singleFile.name" in my Jade template. app.post('/ftp/login', function(req, res){ ftp.ls(" ...

Switching between numerical and alphabetical input using JQuery

How can I switch between allowing character and numeric input in a textbox? I currently have a JQuery function that restricts input to numbers only $('.numeric').on('input', function (event) { this.value = this.value.replace(/[^0 ...

Cannot trigger a click event on nginclude in AngularJS

I have a question regarding including a new page using the nginclude directive. The click event defined in the included page is not working properly. Main Application: <div ng-app=""> <input type="text" ng-model="ss"/> <div ...

Having trouble updating the value of my textfield in material-ui using formik

Below is the code I'm working with to set a default value using the material-ui Textfield API within a formik fieldarray: <TextField name={`myGroups.${index}.myGroupName`} value={`Group ${index+1}`} label="Group" InputProps={{ ...

Error: AJAX response shows as NaN, indicating that the requested resource was not found

Attempting to create a search engine using AJAX. When typing in the search box, nothing happens. After inspecting the element and opening the console, an error message is displayed: script.js:19 GET http://localhost/var/www/html/pendaftaran-siswa/NaN 404 ( ...

The Application Insights Javascript trackException function is giving an error message that states: "Method Failed: 'Unknown'"

I've been testing out AppInsights and implementing the code below: (Encountering a 500 error on fetch) private callMethod(): void { this._callMethodInternal(); } private async _callMethodInternal(): Promise<void> { try { await fetch("h ...

The page's dimensions exceed the size of the device screen

I created this basic HTML content using React <!doctype html> <html><head><title data-react-helmet="true"></title><style type="text/css" data-styled-components="" data-styled-components-is-local="true"></style>< ...

URL Construction with RxJS

How can I efficiently create a urlStream using RxJS that incorporates multiple parameters? var searchStream = new Rx.ReplaySubject(1); var pageStream = new Rx.ReplaySubject(1); var urlStream = new Rx.Observable.create((observer) => { //Looking to ge ...

Can JSF Ajax be used to update non-JSF components like plain HTML elements?

Is it feasible to make changes to sections of my webpage that are not JSF elements? For instance, can I modify a simple HTML <div> or should I enclose it in a JSF component? ...

Is there a way to dynamically assign the background color of a webpage based on the exact width and height of the user's screen?

I have customized the CSS of my website by setting the height to 800px and width to 1050px. Additionally, I have chosen a blue background-color for the body tag. It is important that the entire application adheres to these dimensions. However, when viewe ...

Vue.js Components Facing Build Issues

I am currently experiencing a puzzling phenomenon. While working on my application components using Laravel Jetstream and Inertia Stack with VueJS, I encountered an issue where a newly created component in the same folder as others was not building. Neithe ...

Exposing the secrets of the Ajax module

Here is the code snippet I am working with: my.data = function () { var getAuth = function (userName, password) { var model = JSON.stringify({ "UserName": userName, "Password": password }); var result; $.ajax({ url: m ...

What should I do to resolve the issue of ajax failing to update data randomly?

This script is designed to take the value entered into an HTML form and send it to the ../Resources/BugReport.php file. The data is then inserted into a database in that file, and the table in the ../Resources/BugDisplay.php file displays the information f ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: Here is what I have been able to achieve: In the second picture, the divs are shown separately. My goal is to display the incoming data in a single popup like in the first picture, but I am having trouble a ...

Guide to triggering an API call upon changing the value in a Vue Multiselect component

Is there a way to trigger an API call when the value changes in a Vue Multiselect component? I want to update the value in the multiselect, make an API call, and display the result in the console. Below is my code snippet. <template> <div> ...

How to Extract Minutes in Datatables Timestamps and Apply Custom Styling

Working with Datatables v1.10 Right now, my table is showing a date in the second column in the format 17-04-2019 14:34, which is how it's stored in the database. The filtering and searching functionality are all working as expected. The current HTM ...

Generate responsive elements using Bootstrap dynamically

I'm having success dynamically generating bootstrap elements in my project, except for creating a drop-down menu. ColdFusion is the language I am using to implement these div elements: <div class="panel panel-primary"><div class="panel-head ...