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

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

Uncontrolled discord bot flooding with messages despite being set to send messages only once every 60 seconds

const Discord = require('discord.js'); const { Client, MessageAttachment } = require('discord.js'); const client = new Discord.Client(); client.once('ready', () => { console.log("Ready!") }) client.on(&apos ...

The meter.value update feature is functioning properly, however, it does not refresh the displayed "hover" value

When using JavaScript to update a meter's value, I encountered an issue: var LFRMSMeter = document.getElementById("LFRMSMeter"); LFRMSMeter.value = parseFloat(j[0]); Although the updating of the value works fine, hovering over the meter displays the ...

Adjusting Image Dimensions in jsPDF when Converting HTML to PDF

I have been experiencing some issues with image sizes while using jsPDF to convert HTML to PDF. I am currently on version 1.3.4 of jsPDF and below is the code snippet for reference: const tempElement = document.createElement("div"); tempElement. ...

At what point does IE7 recalculate styles? It seems to have difficulty functioning consistently when a class is applied to the body

Currently facing a peculiar issue. I'm utilizing a class on the element as a toggle switch to control various layout behaviors on my website. When the class is active, specific actions occur; when it's inactive, these actions do not take place. ...

What is the most efficient way to substitute text within an HTML document?

Is there a way to switch between languages on a website to replace text on multiple pages with a simple button click? What is the most efficient method for achieving this? This code snippet only changes text in the first div. Is there a way to implement a ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

Exploring various ways to implement HTTP GET requests within the PrimeVue DatatableUsing a mix

I am facing a challenge where I need to use different GET requests to populate my Datatable with data from separate tables in the Database. Despite trying different approaches, I am unable to figure out how to make this work successfully. I have realized t ...

The error message "reload is not defined" indicates that the function reload

Initially, I encountered the error TypeError: require(...) is not a function, prompting me to add a semicolon at the end of require("./handlers/slashcommands"). However, this led to a new issue: ReferenceError: reload is not defined. This occurre ...

Ajax Complete adds Jquery two times in a row

I have a simple ajax complete call that is designed to add some text after an ajax load finishes. However, I'm encountering an issue where the information is sometimes displayed multiple times. I suspect there might be something missing in my approach ...

Enhancing many-to-many relationships with additional fields in Objection.js

I have a question that I haven't been able to find a clear answer to in the objection.js documentation. In my scenario, I have two Models: export class Language extends BaseId { name: string; static tableName = 'Languages'; st ...

Reloading issue with NextJs when utilizing next-i18next for translations on a specific

Having trouble with next-i18next in my app. Implemented everything correctly, but the layout keeps rerendering on pages with getStaticProps. Need to find a way to prevent this. Created a file named withStaticTranslations.ts for pages, but when trying to l ...

Select component experiencing issue with Material Ui label breaking

I've been working on implementing a select component, which is new to me. However, I'm encountering an issue with my MUI-select component. The label of the select element is no longer syncing properly with the select component itself as shown in ...

Struggling with grasping the concept of promises in AngularJS

I encountered a challenge while working with AngularJS & REST. My data service was not returning data in time for my model to use, despite implementing a promise. I would greatly appreciate any assistance from those more knowledgeable on this matter. In ...

Building an expansive navigation menu with react-bootstrap

My current project involves creating a mega menu. Although I successfully made a responsive navbar, the challenge now is to implement a dropdown panel with 100% width. I've tried various approaches but haven't found one that works. Note: The oth ...

Executing a function defined in a .ts file within HTML through a <script> tag

I am attempting to invoke a doThis() function from my HTML after it has been dynamically generated using a <script>. Since the script is loaded from an external URL, I need to include it using a variable in my .ts file. The script executes successfu ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

Interacting between frames with jQuery

I have main_page.htm with the following frameset structure: <frameset rows="30,*" frameborder=0 border=0> <frame name="top_frame" src="top.htm"> <frame name="bottom_frame" src="bottom.htm"> </frameset> The content in ...

Retrieve the current URL upon page load

I'm currently attempting to parse the URL in document.ready() so I can retrieve the id of the current page and dynamically populate it with content from an AJAX call. However, I've encountered an issue where 'document.URL' seems to refe ...

Height adjustment for flexbox children

Can someone assist me with marking up a todo list? I am attempting to set the height of div.main-tasks equal to div.tasks so that the former fills the entire latter. Unfortunately, I am unsure how to achieve this. You can refer to the following image for c ...