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

What is the process for updating a database using a web browser in Django?

I've completed the ADDING stage successfully, but I'm facing a roadblock in the EDITING stage. The objective is to empower the admin to modify the specifics of a specific member via the browser. Any suggestions? While I've made progress with ...

Add a div element only if there is a background image present

I am facing a situation where I need to display an image as the background of a div only if it is available. If the image is not present, I do not want the div to be visible at all. I am working with django templates and here is my current approach: {% if ...

What's the best approach for implementing TimeInput exclusively in React-Admin?

I discovered this helpful code snippet on the React-Admin documentation that allows me to input both a date and time: import { DateTimeInput } from 'react-admin'; <DateTimeInput source="published_at" /> But now I'm wonderin ...

In Javascript, the DOM contains multiple <li> elements, each of which is associated with a form. These forms need to be submitted using AJAX for efficient

I have a list element (ul) that includes multiple list items (li), and each list item contains a form with an input type of file. How can I submit each form on the change event of the file selection? Below is the HTML code snippet: <ul> ...

Steps to assign a value to a variable upon clicking on text

Struggling to create a form using HTML, CSS, and PHP. The concept involves selecting an option from a dropdown menu and picking a date on a calendar. However, the challenge lies in sending a value to a variable in PHP upon clicking a day. Once the value ...

What is the method for writing to an HTML file with the use of expressjs?

Alright, I have an interesting idea here. I am looking for a way to allow users to push a button and have a new p element permanently added to the HTML file. This means that even after reloading the page, everyone should be able to see this new element. An ...

The ENOENT error code 4058 occurred while attempting to create a new react application using

Every time I run the command npm create-react-app my-app, I encounter an error like this: npm ERR! code ENOENT npm ERR! syscall spawn C:\Windows\System32; npm ERR! path C:\Users\Administrator\Documents\th-wedding\templa ...

Is there a way to customize the hamburger icon for the navigation bar in Bootstrap 4?

Struggling to update the icon in the Navbar for bootstrap 4. Here's my current HTML: <nav class="navbar fixed-top navbar-expand-md navbar-custom"> <a class="navbar-brand" href="#"> <img src="images/logo.svg" width="60px" style="m ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

Is it possible to include spaces in a JavaScript alert message?

Is it possible to add spaces in an alert message? I have been trying to include spaces in my alert messages, but the alerts do not appear when there are spaces. Example where it works: https://jsfiddle.net/yczrhztg/ Example where it doesn't work: ht ...

Firefox won't trigger the `beforeunload` event unless I interact with the webpage by clicking on it

In my quest to handle the beforeunload event in Firefox, I've encountered a small hurdle. It seems to be working smoothly, but only if the user physically interacts with the page by clicking on it or entering text into an input field. Below is the co ...

Is there a way to restore a minimized min.css file?

Recently, I attempted to utilize an online tool for unminifying my CSS code. However, when I replaced the minified code with the unminified version and accessed the URL, I discovered that the entire website had lost its layout. Unfortunately, relying sole ...

Seeking assistance with dilemmas related to jQuery (specifically kendo), .NET Web Service (asmx), and Json

After conducting extensive research on the subject, I was unable to find any satisfactory answers or complete examples. Since I have limited experience with jquery, I am in search of a straightforward sample that demonstrates what I'm trying to achiev ...

Is it possible to enable unknown keys for multiple schema objects simultaneously using Joi Validation?

I have a multitude of validator files each containing nearly a hundred schema objects. My goal is to validate unknown keys for all of them simultaneously. I've managed to figure out how to do it for a single object, as shown below. Is there a way to a ...

Break down a string into an array containing a specific number of characters each

I'm currently working on a project that involves tweeting excerpts from a book daily via a small app. The book's content is stored in a text file and I need to split it into 140-character-long strings for posting. Initially, I tried using the s ...

The drag and drop feature seems to be malfunctioning in the Selenium Webdriver when using the Node.js (JavaScript) test automation framework

I am currently utilizing the selenium webdriver along with a customized automation framework built in nodejs. My goal is to implement drag and drop functionality for a slider using the actions class, but unfortunately I am encountering issues. Below you ca ...

Maximizing jQuery DataTables performance with single column filtering options and a vast amount of data rows

My current project involves a table with unique column select drop-downs provided by an amazing jQuery plug-in. The performance is excellent with about 1000 rows. However, the client just informed me that the data could increase to 40000 rows within a mont ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

What is the best way to align a dropdown menu and a textbox on the same line

I have recently been working on a search bar that includes a Dropdown for Location and a Textbox for Search. Prior to implementing bootstrap, these elements were displayed in a single line. However, after applying bootstrap, they are now stacked vertically ...

Extracting Data from Imgur Videos: Measuring their Duration

Hey there! Lately, I've been faced with the challenge of extracting specific information from videos hosted on the imgur website. Specifically, I'm interested in retrieving the video length indicated in the attached image. Despite my best efforts ...