JavaScript to toggle the visibility of elements when they move outside of a specified container

Check out this js+html/css project I worked on: http://jsfiddle.net/A1ex5andr/xpRrf/ It functions as intended - opening and closing with the use of .advSearch-btn to open/close, and .advSearch-control .canc to close. However, I am facing an issue where it doesn't close when clicked outside the <div class="advSearch">

Here is the HTML code:

<div class="advSearch">
   <span class="advSearch-btn">Advanced Search</span>
  <div class="advSearch-container">
    <div class="col left">
      <h3>Customer</h3>
      <form action="">
        <label><h4>First Name</h4> <input type="text"> </label>
        <label><h4>Last Name</h4> <input type="text"> </label>
        <label><h4>Email</h4> <input type="text"> </label>
        <label><h4>Phone</h4> <input type="text"> </label>
      </form>
    </div>
    <div class="col central">
      <h3>Address</h3>
      <form action="">
        <label><h4>Adsress</h4> <input type="text"> </label>
        <label><h4>City</h4> <input type="text"> </label>
        <label><h4>State</h4> <input type="text"> </label>
        <label><h4>Zip</h4> <input type="text"> </label>
      </form>
    </div>
    <div class="col right">
      <h3>Other</h3>
       <form action="">
        <label><h4>Policy</h4> <input type="text"> </label>
        <label><h4>App ID</h4> <input type="text"> </label>
        <label><h4>Quote</h4> <input type="text"> </label>
        <label><h4></h4> <input type="text"> </label>
      </form>
    </div>
  <div class="advSearch-control">
    <button class="canc">Cancel</button>
    <button class="srch">Search</button>
  </div>
  </div>
</div>

This is the working JavaScript code:

 // advanced search show/hide and buttons callBack
    var container = $(".advSearch-container");
    // Bind the link to toggle the slide.
    var slideAdvancedSearch = function() {
        // Toggle the slide based on its visibility
        if (container.is(":visible")) {
            // Hide - slide up.
            $('.canc').css('display', 'none');
            $('.srch').css('display', 'none');
            container.slideUp(1000);
        } else {
            // Show - slide down.
            container.slideDown(1000, function() {
                $('.canc').css('display', 'inline-block');
                $('.srch').css('display', 'inline-block');

                // $(document).click(function() {
                //     if (container.is(":visible")) {
                //         container.fadeOut(300);
                //     } else {
                //         e.stopPropagation();
                //         console.log('its stoped');
                //     }
                // });

                // $(document).click(function(event) {
                //     if ($(event.target).parents().index(container) == -1) {
                //         if (container.is(":visible")) {
                //             container.hide()
                //         }
                //     }
                // })

            });
        }
    };

    //run slide on AdvSearch button
    $(".advSearch-btn").click(function() {
        slideAdvancedSearch();
    });

    //run slide on Cancel button
    $('.canc').click(function(event) {
        slideAdvancedSearch();
    });

    // Modified Date sort arrow
    var sortArrow = $('.sortArrow');
    sortArrow.click(function(event) {
        $(this).toggleClass('up');
    });

I've attempted these methods for closing on click outside the div: (commented in code that works)

             $(document).click(function() {
                 if (container.is(":visible")) {
                     container.fadeOut(300);
                 } else {
                     e.stopPropagation();
                     console.log('its stoped');
                 }
             });

or

             $(document).click(function(event) {
                 if ($(event.target).parents().index(container) == -1) {
                     if (container.is(":visible")) {
                         container.hide()
                     }
                 }
             })

The question is what could be the issue here? Thank you for your help in advance.

Answer №1

Here is a helpful suggestion. Remember, there's no need to trigger the event when the advanced search is visible. Simply ensure it loads as usual:

$(document).click(function(e) {
    if($(e.target).parents('.advSearch').first().length == 0)
        container.fadeOut(300);
});

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

When attempting to click the submit button, the action of submitting a form using jQuery/AJAX is not functioning as expected

When attempting to submit a form using jquery/AJAX, my function does not get called when clicking on the submit button. The structure of my website is as follows: CarMenu.php <html lang="en"> <html> <head> <meta charset="ISO-8859- ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

Steps to eliminate the 'Edit Translation' text on Transposh

Attempting to eliminate the 'Edit Translation' text provided by Transposh to maintain the existing translations. Implementing CSS code like so: #transposh-3:nth-child(8){display:none;} and localizertextnode{display:none;} However, these styl ...

Utilize the three.js library within a Vue component by importing it and incorporating its

Can someone please help me understand the proper way to import and utilize the three.js library in a vue component? Despite my extensive research, it seems that most individuals use the following code line to import three.js into a vue component. However, ...

JavaScript or Query: Transforming an Object from an Associative Array

Can someone help me out with converting an associative array into an object in JavaScript? I tried searching on Stackoverflow but couldn't find a working example. Here is the example structure: var combinedproducts = [["Testing-1","test-1"],["Testin ...

generate a new entry at the end of the list

I have a list and I am attempting to generate an element when the last row is clicked. It's a bit hard to explain, so here is the link to the jsfiddle: http://jsfiddle.net/ckgL3zxd/4/ When you click on the last row, you will notice that the element w ...

What methods can be used to customize the font and background color of a website for different user groups?

Trying to incorporate a template into my project. My client has requested the following: The regular user area should feature a blue background. The professional user area should have an orange background. Is there a way to set up a condition to change ...

I am encountering an issue with the return ( statement and I'm unable to comprehend the reason behind it

import { connect } from 'react-redux' import { Link } from 'react-router-dom' class MyFavoriteStories extends React.Component { markAsFavorite = (e) => { this.setState({ bgColor: "blue" }) } render () { con ...

Animate the smooth downward movement of a div element with real-time updates using JQuery

I attempted to create a dynamic list that updates from the top. Each time a new item is added, all previous items smoothly move down. Initially, I added a new list item every time I clicked: function addItem(){ $('#public').prepend('< ...

Webpack-dev-middleware is serving the bundle on a port that is distinct from the application

Recently, I've been developing a React boilerplate that fully utilizes Apollo-Client and GraphQL. The setup of my application consists of one node process overseeing an Express server on port 3000 to render the app, and another Express server on port ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

Discovering the method to extract a Specific Form Field value with JQuery

Recently, I encountered a form that looked like this: <form id="post_comment" action="cmt.php" method="post"> <input type="hidden" name="type" value="sub" /> <textarea id="body"></textarea> </form> To interact with the ...

Loading JSON data in AngularJS before parsing and loading HTML content from it

Greetings, I am new to Angular and seeking some guidance. My goal is to limit a list of notifications to three using limitTo, and then load the rest when a button is clicked. Currently, I am unsure about the following: How to set up the "view" and appl ...

The process of displaying a single large image from a local file system using the elements input, img, and canvas

I am attempting to create a mobile-friendly picture upload webpage, but I keep experiencing memory issues causing the browser to crash when the picture is too large. Here's my code: <input type="file" id="testFile" /> <img src="" style="posi ...

Failure to recognize AJAX content in .ready function

When using an AJAX call to load content, primarily images, I encountered a challenge. I wanted the div to fade in only after all the images were fully loaded. To achieve this, I made use of .ready method in jQuery. However, it seemed like the images were n ...

Efficiently Encoding Still Image Data for NextJS

Currently, I am experimenting with a completely static method in my new Next.js v12 project. I am creating 5-6 data files to use with getStaticProps. Here is an example of one of the data file structures (they are all similar): import SqAshland1 from &apos ...

One-way communication between two clients using Socket.io

While working on a basic socket.io application using React and Express, I've encountered an issue where two clients are facing difficulties in sending data to each other. For instance: Player 1 connects to the server followed by Player 2. Player 1 ...

What could be the reason my span is not altering color as I scroll?

Important HTML Knowledge <section class="home" id="home"> <div class="max-width"> <div class="home-content"> <div class="text-1">Hey t ...

The function in an AngularJS controller is failing to execute

I am experiencing an issue with calling the checkLogin function of a controller. The value returned by checkLogin is used to show/hide elements with ng-show. However, when debugging, I noticed that the execution stops after the function call and does not p ...