When using jQuery's `.click()` method on an element to collapse it with the 'show' parameter set to false, the disabling action will only take effect after the document

When you first run the program and click anywhere on the body, it activates the collapse element. I want it to only collapse the accordion on click, not show it immediately. Currently, it will deactivate only after it is hidden once.

HTML


<!DOCTYPE html>
<html>
    <body>
        <div class="accordion" style="z-index:9999">
            <div class="panel contact-panel">
                <div class="panel-heading accordion-toggle collapsed" role="tab" id="headingTwo" data-toggle="collapse" data-parent="#accordion" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" style="color:#fff!important;">    <span><h5 style="margin-bottom:0!important;"><i class="fa fa-envelope">&nbsp;</i>Your Title here</h5></span>
                </div>
                <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
                    <div class="panel-body">
                        <form class="form-horizontal" role="form" method="post" action="" id="contactForm" name="contactForm">
                            <div class="form-group">
                                <label for="name" class="col-sm-3 control-label">Name</label>
                                <div class="col-sm-9">
                                    <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="" />
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="email" class="col-sm-3 control-label">Email</label>
                                <div class="col-sm-9">
                                    <input type="email" class="form-control" id="email" name="email" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91f4e9f0fce1fdf4d1f5fefcf0f8ffbff2fefc">[email protected]</a>" value="" />
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="message" class="col-sm-3 control-label">Message</label>
                                <div class="col-sm-9">
                                    <textarea class="form-control" rows="4" name="message" placeholder="Message Content Here"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="human" class="col-sm-3 control-label">Are You <strong><u>Human</u>?</strong>

                                </label>
                                <div class="col-sm-9">
                                    <input id="field_human" class="field_human" type="checkbox" name="human" />
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-9 col-sm-offset-3">
                                    <button id="submit" name="submit" type="submit" class="btn btn-dark btn-block btn-lg">Send</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

CSS


.row > p{
    padding:2%;
    border:1px solid #eee;
    border-radius:10px;
    background:#eee;
}
.accordion {
    width:100%;
    position:fixed;
    bottom:-2.1%;
    margin-bottom:0;
    padding-bottom:0;
}
.accordion label {
    color:#fff;
}
.accordion input {
    border-radius:0;
}
.panel-heading, .panel-heading:hover, .panel-heading:focus, .panel-heading.focus, .panel-heading:active, .panel-heading.active {
    cursor:pointer;
    background-color: #c9302c;
    border-color: #ac2925;
    outline:none;
}
.accordion-toggle {
    text-align:center;
}
...... (remaining CSS code)

JavaScript


// This section contains the JavaScript code logic that operates the functionality of the accordion component.

// If needed, add some unique description or notes about this part of the code.
...... (add more unique content)


FIDDLE

Answer №1

Before hiding the collapse element, it's a good idea to check if it already has the class in.

 $(document).on('click', function (e) {
        // Target => collapse('hide')
         if($('#collapseTwo').hasClass('in') && $(e.target).closest('.form-horizontal').length==0) {
             $('#collapseTwo').collapse('hide');
        }
        //stop the code from bubbling up
        e.stopPropagation();
        e.preventDefault();
    });

Check out this Fiddle Demo for more

Answer №2

Simply include the line

$('#collapseTwo').collapse('hide', true);
in your code to resolve the issue.

$(document).on('click', function (e) {
        // Target => collapse('hide')
       // $('#collapseTwo').collapse('hide', true); //commented this line.
        //stop the code from bubbling up
        e.stopPropagation();
        e.preventDefault();
    });

View the solution on Fiddle.

Edit:

To fix the problem, add the following jQuery code snippet:

$('#collapseTwo').on('click', function (e) {
        $('#collapseTwo').collapse('hide', true);
    });

Updated version on Fiddle.

Check the following if statement:

if ($('#collapseTwo').is(':visible'))
   {
    $('#collapseTwo').collapse('hide', true);
   }

View on Fiddle.

Answer №3

It is not recommended to use preventDefault() on the document click trigger as it can cause issues with external links. I have removed the prevent default and now all my links work properly by using easyScroll(). Check out the code below for more details:

//find and uncheck all checkboxes
var checkboxes = document.getElementsByTagName('input');

for (var i = 0; i < checkboxes.length; i++)
{
    if (checkboxes[i].type == 'checkbox')
    {
        checkboxes[i].checked = false;
    }
}

$(document).ready(function()
{
    var $checked = $('#field_human');

    $("#submit").attr("disabled", !$checked.checked)
    
    $checked.click(function()
    {
        if ($checked.prop('checked'))
        {
            $('#submit').removeAttr('disabled');
        }

        else
        {
            $("#submit").attr("disabled",!$checked.checked);
        }
        
        return;
    });

    $('.accordion').on('mouseenter', function()
    {
        $('#collapseTwo').collapse('show');
        return false;
    });

    $('.accordion').on('click', function(e)
    {
        $(this + siblings).collapse('hide', false);
        e.preventDefault();
    });

    $(document).on('click', function(e)
    {
        if($('#collapseTwo').hasClass('in') && $(e.target).closest('.form-horizontal').length==0)
        {
            $('#collapseTwo').collapse('hide');
        }
        
        e.stopPropagation();
    });
});

You can view the working example on my website at Soldier-up Designs

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

Save mathematical equations written in HTML text boxes to a MySQL database

How can I display mathematical formulas in a text input and store them in a database? I need to be able to display formulas like the ones shown in the image at this link: Currently, when I copy any formula into the text box, it gets converted to normal t ...

What are the various ways to incorporate material graphic elements on an HTML static webpage?

Currently, I am working on creating a static website that will be stored on CDs and USB sticks. This website serves as a manual for a specific product. I am considering using a graphic framework like Onsen UI, but I have found that I prefer Material UI. ...

What is the best way to explain the concept of HTML5?

While reading a question on Stack Overflow, I came across a comment that stated: HTML5 is equal to HTML(5) + CSS3 + JavaScript. This statement truly caught me by surprise. Can it really be argued that HTML5 can be broken down into HTML(5), CSS3, and Ja ...

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...

Create a single button that controls checkboxes with the help of HTML, CSS, SCSS, and Bootstrap 4

Is there a way to use only HTML, CSS, SCSS, and Bootstrap 4 to make all checkboxes default to the "on" condition when a button is clicked? Typically, this functionality would be achieved with JavaScript, but due to constraints, I am exploring alternative ...

User authentication on AngularJs is only initiated on the second interaction

My personally built AngularJs user authentication system is experiencing an unusual issue. While everything seems to be working fine - I can login, check access for specific pages, etc. - there is a strange behavior with the token authentication. It seems ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Looking for a solution to organize the dynamically generated list items in an HTML page

I am currently working on a movie listing website where all the movies are displayed in sequence based on their #TITLE#. The webpage is generated automatically by the software using a template file. Here is the section of code in the template file that sho ...

Utilizing jQuery to append a function to an object and subsequently initiate an event on it

In the scenario presented, I have a jQuery Object called $wrapper = $(this);. This occurs within an init call as shown here: $('#unique-wrapper-id').initWrapper()'. The initWrapper() function is part of jQuery.fn. Within the initWrapper() c ...

AngularJS is encountering an issue with the callback function, resulting in an error

Currently, I am utilizing the $timeout service in Angular to decrease a variable from 100 to 1 in increments of 1/10 seconds. Although I understand that using the $interval service would be a simpler solution, for this particular scenario, I am focused on ...

Tips for using Selenium and Javascript executor to search through the Canvas system?

Is it possible to automate interaction with a 'graph' created on a canvas? I need to be able to click on elements, drag them, and perform other actions like getting text. Can this be achieved with automation using Selenium and JavaScript executor ...

In JavaScript, a true statement does not trigger a redirect

<label>Username:</label> <input name="username" id="username" type="text" value="testuser"> <label>Password:</label> <input name="password" id="password" type="password" value="test123"> <input value="Submit" name="su ...

Switching the placement of my menu bar to the other side of my logo

Can anyone help me figure out how to move my menu bar to the opposite side of my logo? I attempted using the position relative in CSS but it didn't reposition correctly. I've included the position:relative in the CSS code of my HTML index file, ...

Executing a JavaScript command to execute a PHP script and subsequently inserting HTML content into the appropriate row

Here is an easy-to-follow guide... Essentially, I have created an order form that initially consists of one row. <form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post"> <a id="add">+</a> <table id ...

Navigating a single page application with the convenience of the back button using AJAX

I have developed a website that is designed to function without keeping any browser history, aside from the main page. This was primarily done for security reasons to ensure that the server and browser state always remain in sync. Is there a method by whi ...

Using Jquery to target an element within the same DOM element and apply changes

My website platform doesn't assign any IDs or classes to the menus it generates, and uses nested lists for submenus. To make the submenus expand upon clicking, I created a jQuery script: $(function () { $(".wrapper ul li").click(function () { ...

Typescript MUI Autocomplete: Can you specify the parameter type of the PaperComponents function?

If you use MUI's Autocomplete, there is a property called PaperCompomponent that allows you to pass your own react component. This property is a function with properties as a parameter, which can then be used to pass on to your custom component. In T ...

Undefined type in JavaScript

Below is the JavaScript code snippet I have written. function bar() { var x = "Amy"; x = parseInt(x); console.log(x); if (isNaN(x)) { console.log("Your entry is not a number"); } else { if (typeof (x) === "number") { console.log("number" ...

Does IE 9 support Display Tag?

Although this may not be directly related to programming, I have been unable to locate any information regarding the compatibility of IE 9 or even 8 with the Display Tag Library. The documentation is silent on the matter. If anyone has encountered any cha ...

Send information from the textbox

I am trying to extract data from an input field and use it to create a QR code. While passing the value as text works, I am facing issues with passing the actual input value. Does anyone have a straightforward example of this process? import React, {Comp ...