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

I'm having some trouble with jQuery's GET function while working with CodeIgniter. Instead of retrieving a single value, it seems to be returning the source code for a

I have been experimenting with the jQuery GET method, but the results are not what I expected. My goal is to call a function from my controller using jQuery and display the returned value in a specific div within my view. Below you can see the code snippet ...

Some elements are not responding to margin-top properly

I am facing a problem where 2 elements are not responding to the specified margins of margin: 260px 0 0 0; or margin-top: 260px;. Despite inspecting the elements in IE's dev tools and confirming that the margin is set, the elements appear at the top o ...

Is there a way to prevent hover effects on the outer div when hovering over the inner div?

I am facing an issue with disabling hover effects on an outer div when hovering over an inner button. I have tried various methods but haven't been successful in achieving the desired outcome. .container { background-color: #e6e6e6; width: 400p ...

The results of running 'npm run dev' and 'npm run build prod' are different from each other

Currently, I am in the process of developing a progressive web app using Vue.js. During development, I utilize the command npm run dev to initiate the local server that serves the files over at http://localhost:8080/. When it comes time to build for produ ...

The HTML object is experiencing difficulties with the Ajax page loader feature not functioning as

I attempted to use the code below in order to show an Ajax loader image while the page loads into an HTML object. Unfortunately, it didn't work as expected and I'm having trouble figuring out why. Everything seems to be functioning correctly exce ...

Issues arise when attempting to use Stylus in conjunction with React

I am currently working on developing a web application that utilizes Stylus and React. I have successfully rewritten all the Stylus language files, but I am encountering an issue where the React components are not being styled as expected. Below is one of ...

creating a div that functions similarly to a radio button

Is it possible to create a div that mimics the behavior of a radio button? I'm looking for a solution that doesn't involve jquery, as many people have recommended. After doing some research, I found a few potential options. In the past, I'v ...

The outcome of jQuery's division and multiplication is not correct

When a user inputs data into the form fields, the other fields should be automatically filled with the calculated values. However, it appears that jQuery is treating the input values as strings instead of numbers, leading to incorrect calculations. I&apos ...

What could be the reason for my code showing "success" instead of the intended outcome?

I'm currently working on a project that focuses on verifying whether ingredients are halal or haram. MongoDB is being used to store ingredient information, and express is managing the requests. After sending a GET request to /ingredients/{ingredientn ...

Unable to relocate CSS Loader Container

Can someone help me with adjusting the placement of my container? I'm struggling to maintain the styles while getting rid of the position: absolute; on the .dot class. Every attempt I make is resulting in the dots moving erratically! To clarify, I w ...

How far apart are two surfaces when they are rotated along the Y-axis

Access Code: Click here to access the code I am trying to make sure that the red surface lies completely flat on top of the gray surface. However, there seems to be a gap (marked ??) between the two surfaces when I rotate 'modifier1'. How can I ...

The window fails to retain the scroll position when overflow is enabled

Whenever I click on a specific div, I use jQuery to dynamically apply overflow: hidden to the html and body. $(".mydiv").on("click", function() { $("html, body").css("overflow", "hidden"); }); However, this action causes the window to scroll to the to ...

Navigate to the top of the page using jQuery

Attempting to implement a simple "scroll jump to target" functionality. I've managed to set it up for all parts except the "scroll to top". The jumping works based on the tag's id, so it navigates well everywhere else, but not to the very top. He ...

Animate the jQuery element to fade in after it has been hidden with the slide effect

I am trying to create a div that slides out of the viewport and then fades in at the same spot with a different background image. However, currently it only slides out and does not fadeIn: $('#myDiv').hide('slide').queue(function() { ...

What is the best way to customize the style of a react.js component upon its creation?

Is there a way to set the style of a react.js component during its creation? Here is a snippet of my code (which I inherited and simplified for clarity) I want to be able to use my LogComponent to display different pages of a Log. However, in certain ins ...

Concealing a hyperlink within a DIV by removing or hiding it

I am looking to temporarily hide or remove a specific link (team.aspx) within a drop-down menu, with the intention of adding it back in later. Here is my current code: <div id="nav_menu"> <ul id="nav"> <li class="current"><a href= ...

Tips for updating the content within an HTML tag with jQuery

I am looking to update the parameter value of an applet tag based on the selection from a dropdown menu. As I am new to jQuery, I would appreciate any guidance on how to achieve this using jQuery. This is my current applet code: <applet id="decisiontr ...

Scrolling behavior in two columns with sticky positioning

Both columns have varying heights, with the left sometimes higher than the right. I want them to start scrolling down simultaneously, but when the shorter column's content ends, it should stick to the bottom of the viewport and "wait" until the taller ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Using Jquery fadeIn along with responsive CSS media queries

Issue at Hand: An issue arises with my navigation bar and text block animations. The fading effect applied on the text element causes inline styles to be added, thus disrupting the media query set to hide the text on smaller screens. If you disable the s ...