Hiding a div becomes impossible once it has been set to display:block

When I click on an element, I want a box to open and then when I click on a "CLOSE" button, I want it to disappear. However, I am encountering an issue where the box appears using "display:block" but does not disappear with "display:none" as intended (see enclosed code).

I also attempted using addClass and removeClass with a CSS attribute like display:none, but that did not work either.

<html>
    <head>
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
        <style>
            div.back {  
                float: left;
                background-color: grey;
                width:100px;
                height:100px;
                margin:10px;
                padding:10px;
            }
            .window {
                display: none;
                position: fixed;
                top: 150px;
                left: 150px;
                width:150px;
                height:100px; 
                background-color:blue;
            }
        </style>
        <script>
            $(document).ready(function(){
                $(".back").click(function(){       
                    $(".window").css("display","block");     
                });
                $(".btn_validate").click(function(){        
                    $(".window").css("display","none");              
                });
            });
        </script>
    </head>
    <body>
        <div class="back">
            Some text
            <div id="draggable" class="window">
                <input type="button" value="CLOSE" class="btn_validate"/>
            </div>
        </div>
    </body>
</html>

Answer №1

Yes, it may appear hidden initially, but it quickly reopens because the click propagates up and triggers a click on the parent element. To prevent this behavior, utilize e.stopPropagation();:

$(".btn_validate").click(function (e) {
    e.stopPropagation();
    $(".window").css("display", "none");
});

Check out this jsFiddle example for reference.

Answer №2

The element is initially hidden due to the CSS setting display: none, but it quickly reappears because of the click event bubbling up to the parent .back element.

To prevent this, you can use either e.stopPropagation() or return false; (which in a jQuery handler is equivalent to e.stopPropagation() and e.preventDefault()). Check out this example

$(".btn_validate").click(function(){        
      $(".window").css("display","none");              
      return false;
});

Alternatively, you can do this (example)

$(".btn_validate").click(function(e){        
      e.stopPropagation();
      $(".window").css("display","none");              
});

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

Is it possible to constrain jQuery Draggable elements within the boundaries of the

I need to restrict my draggable element so that it stays within the viewable window. It works fine when the user is at the top of the page, but as soon as you scroll down, it gets messed up. Do you know how I can fix this issue? $(".chat-wrapper > li. ...

Tips for How to Put a Delay on Ajax Requests and Display a Progress Bar During Loading

I am using checkboxes in the sidebar. When a user selects a checkbox from the sidebar, it displays the post normally. Is there a way to add a progress bar to delay the Ajax result? This is my Ajax code: <script> jQuery(document).ready(function($){ ...

Issue encountered while attempting to generate a Jquery button

I seem to be facing some difficulties as I have successfully completed this task before. Currently, I am dynamically adding HTML code: ...<td><label><input type=\"checkbox\" checked=\"checked\" class=\"Activechk fo ...

The AJAX calendar control remains unchanged after a reset

I am currently facing an issue with my ajax calendar control used in a form for selecting dates. The problem arises when I select a date from the previous year and then click on the reset button. Even though the text box is cleared, the calendar control s ...

Artistic Canvas: Selected Image

I am trying to determine if the user has clicked on an image drawn in a canvas element. Despite clicking on the image, nothing seems to be happening. The alert function is not being triggered and the last condition in the code never evaluates to true. An ...

Incorrect placement of navigation in HTML/CSS dimensions

I'm working on my new portfolio and I've run into an issue with the navigation placement that I can't seem to solve. The text should be aligned with the lines on the sides, but instead it's shifted right and down. I'm struggling t ...

Customize the Kendo UI by integrating it with HTML tables and dropdown lists

I am trying to utilize an HTML table as the data source for kendo-ui jQuery, and also enable inline editing with a drop-down list. To achieve this, I have written the code below: However, my issue arises when a user double clicks on a row of the table to ...

"Creating a link to a button with the type of 'submit' in HTML - a step-by-step

Found the solution on this interesting page: In a list, there's a button: <form> <ul> <li> <a href="account.html" class="button"> <button type="submit">Submit</button> ...

Bootstrap 4's form validation feature is malfunctioning

link to plunker Here's what I'm looking to achieve. I am currently using Bootstrap 4 for my website. Specifically, I have a basic contact form that I am attempting to enhance with tooltip validation. Unfortunately, the form validation is not ...

Using JQuery to make POST requests is successful, however, utilizing the XMLHttpRequest object to make

Currently, I am attempting to make a POST request from Javascript to my server in PHP but without utilizing jQuery. The following code successfully sends the required data to the database: var msg = {}; msg['name'] = 'joe'; msg['m ...

A data table created with Bootstrap is not displayed inline with the pagination feature

Customizing Bootstrap Data Table Code Instructions on how to customize this code: <div class="row"> <div class="col-sm-5"> <div class="dataTables_info" id="example_info" role="status" aria-live="polite"> Showing 1 to 10 of 2 ...

Showing a notification that is persistent and not dismissible

Hello everyone! I've been struggling with a problem on the RPS project for quite some time now. The issue arises when I try to display a message for a tie in the game, but I can't seem to find a solution to make it disappear when the round is not ...

Unable to toggle navigation menu visibility on responsive design

I have provided the following code for responsive design. However, when I click the logo, it does not hide or show as expected. .toggle-nav { display: none; } .menu { float: right; } // Additional CSS code here <nav class="menu"> <ul c ...

The differences between xPages and HTML templates are evident in the varying sizes of their elements

When using a html template in an xPages application, I noticed that all elements appear slightly larger compared to a plain html page. Even when checking the values in Chrome debugger, they all seem to be the same. ...

Using jQuery to smoothly scroll to a position determined by a custom variable

Here's the script I am working with: $('.how-we-do-it .items div').on('click', function () { var $matchingDIV = $('.how-we-do-it .sections .section .content div.' + $(this).attr('class')); $matchingDIV. ...

responsive position absolute to the auto width of position absolute

Here is an example of my CSS code: https://jsfiddle.net/80e4u0dd/ When you hover over the orange box, the a element gets underlined. The orange box needs to stay above the "long text" in the green box, just like it is currently. The issue is that the oran ...

Ways to get rid of the white horizontal line generated by bootstrap framework?

I'm currently working on a responsive navbar design and I want it to appear transparent over a background image. However, my front-end knowledge is limited as I've only been learning for a week. Can anyone advise me on how to remove the white bar ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

Extracting a text value from a div using jQuery instead of displaying it in an alert modal

Can someone help me figure out a simple way to display text in a div that indicates what has changed compared to an alert modal with the following code? I'm struggling to understand it. Thanks... $(function(){ var abc = $('selec ...

Ensure that the div remains within the viewport

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Tit ...