When the open button is clicked, the Div will toggle between open and closed states

Recently, some of my questions have not been well-received, which makes me feel a bit disheartened. It's important to remember to be kind when providing feedback. I've noticed that some people downvote without offering constructive criticism, which can be frustrating and may even lead to being blocked from asking further questions. While I admit that not all my posts are perfect, I believe it's unfair for others to overreact to simple mistakes that are easily fixable. With that said, let's move on to the actual question.

TL;DR: Be kind!

I have a "settings" div:

<div id="settings">
    <p><a href="settings.php" class="settings">Search Settings</a></p>
    <p><a href="sync.php" class="settings">Sync Settings</a></p>
    <p><a href="anon.php" class="settings">Go Anonymous</a></p>
</div>

To open this div, I have a button:

<a onClick="openSettings()" href="#" class="footer" id="settings-button">Settings</a>

To make the button functionality work, I'm using some simple JavaScript:

$("html").click(function(){
    $("#settings").slideUp()
});

$("#settings").click(function(e){
    e.stopPropagation();
});

function openSettings() {
    $("#settings").slideDown();
}

Oddly enough, when I click the button, the div opens and then immediately closes again. This behavior perplexes me, as I've tried different solutions including referencing Stack Overflow for help.

Related articles:

jQuery: Hide popup if click detected elsewhere

How do I make this popup box disappear when I click outside?

I'm feeling quite lost at this point and any guidance would be greatly appreciated.

Best Regards, Emanuel

EDIT: I just realized I forgot to share my CSS styling information:

div#settings {
display: none;
position: absolute;
right: 20px;
bottom: 50px;
background-color: #9E9E9E;
width: 200px;
box-shadow: 2px 2px 10px #000000;
border-style: solid;
border-color: #000000;
border-width: 1px;
color: #551A8B;
padding-left: 15px;
}

Answer №1

$("html").click(function(){
    $("#settings").slideUp()
});

It seems like the function is triggered upon clicking on the #settings-button, causing the element to slide up after sliding down, and this behavior occurs with each click on the html element or document.


The intended functionality is for the settings to be hidden by default and slide up when the button is clicked. It should also slide away when you click anywhere outside of it while it's open.

Consider incorporating $(document).one("click", fn) at the .slideDown() callback to make the #settings div slide up when clicking outside of it on the document.


Replace .on("click") with onclick in the html, cache the #settings selector, and invoke .slideDown() and .slideUp() within the openSettings function.

$(function() {

  var elem = $("#settings");

  function openSettings() {
    elem.is(":hidden") 
    ? elem.slideDown(function() {
        $(document).one("click", function(e) {
          elem.slideUp()
        })
      }) 
    : elem.slideUp();
  }

  $("#settings-button").on("click.show", openSettings);

  elem.click(function(e) {
    e.stopPropagation();
  });

});
body {
  width: 100%;
  height: 100%;
}
div#settings {
  display: none;
  position: absolute;
  right: 20px;
  bottom: 50px;
  background-color: #9E9E9E;
  width: 200px;
  box-shadow: 2px 2px 10px #000000;
  border-style: solid;
  border-color: #000000;
  border-width: 1px;
  color: #551A8B;
  padding-left: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="settings">
  <p><a href="settings.php" class="settings">Search Settings</a>
  </p>
  <p><a href="sync.php" class="settings">Sync Settings</a>
  </p>
  <p><a href="anon.php" class="settings">Go Anonymous</a>
  </p>
</div>
<a href="#" class="footer" id="settings-button">Settings</a>

Answer №2

It seems like the stopPropagation function is being applied to the incorrect element, it should be targeted at #menu-button:

$("#menu-button").click(function(e) {
  e.stopPropagation();
});

Demo

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

Position a div adjacent to a particular, changing Rails component once jQuery has toggled it

Within my Rails application (which is utilizing Bootstrap's grid system), I am featuring a blog post within the left column. On the right side, I have integrated a jQuery toggle effect to reveal a quick form for user interaction such as leaving commen ...

Tips for building a versatile client-server application with separate codebases for the JavaScript components

We are embarking on the process of rebuilding our CMS and leveraging our expertise with VueJS. Despite our familiarity with VueJS, we won't be able to create a full single-page application due to the presence of server-side rendering files (JSP). The ...

Thymeleaf causing Spring IO POST form to redirect to incorrect URL

One of the challenges I'm facing while coding a website is with a form for uploading files. Ideally, when accessing the URL http://localhost:8080/uploadRevision/{docId}, it should lead to http://localhost:8080/uploadRevisionLanding and then redirect b ...

MongoDB Client > Error: No operations provided - cannot proceed

NPM Library: "mongodb": "3.1.4" Encountering an issue while attempting to bulk insert a list of data: Here is the code snippet: db.collection('products').insertManyAsync(products, {ordered: false}) The error message displayed: An Invalid O ...

Meteor is failing to update the data in MongoDB

I have encountered an issue with the following code snippet: Nodes = new Meteor.Collection("nodes"); [...] Template.list.events({ 'click .toggle': function () { Session.set("selected_machine", this._id); Nodes.update(Session.get("s ...

Sequencing numerous promises (managing callbacks)

I am encountering some challenges with promises when it comes to chaining multiple ones. I'm having difficulty distinguishing how to effectively utilize promises and their differences with callbacks. I've noticed that sometimes callbacks are trig ...

What is the method for advancing the cursor to the next line in this animation?

I've created an animation that types out: "[Your Name] blah blah" with a typing effect. Now, I want the cursor to move to the next line and type out: "[Your Father Name] blah blah" I attempted to add <br>, but it types out both lines simulta ...

Is there a way to transform my json data into a particular structure?

My json string looks like this: arguments[0] = [{"one":"1","two":"1","three":"15","four":"esj","five":null,"six":"2015-10-15 00:00:00","seven":null}, {"one":"1","two":"1","three":"15","four":"esj","five":null,"six":"2015-10-15 00:00:00","seven":null}, {"o ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Increasing the date field value in Mongoose, ExpressJS, and AngularJS with additional days

I encountered an issue while attempting to extend the number of days for an existing Date field in mongoose. Despite no errors being displayed in the browser or console, something seems to be amiss. Can anyone identify the problem in this code snippet? ...

Unable to successfully implement the Bootstrap dropdown feature in my header upon switching pages

Utilizing Ruby on Rails and Bootstrap 5.3 to develop a website for showcasing my projects and information. I have a header file that contains all of the navbar code. Once I visit any link from one of the dropdown options, the dropdown button stops function ...

What is the best approach to building this using Angular?

Greetings, this marks the beginning of my inquiry and I must admit that articulating it correctly might be a challenge. Nevertheless, here's my attempt: Within the following code snippet, there lies an element that effectively fills up my designated ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

Connecting to a database using Vugen's Ajax TruClient feature

Recently, I've been experimenting with Ajax TruClient, but I'm struggling to find any functions that would enable me to connect to an Oracle database in order to retrieve information and compare it against the UI. Does anyone have any insights on ...

Combining Material UI with React Form Hook to handle multiple checkboxes with pre-selected defaults

I am working on creating a form with grouped checkboxes using react-form-hook and Material UI. The checkboxes are generated dynamically through an HTTP Request. I am aiming to set the default values by providing an array of object IDs: defaultValues: { ...

Exploring the wonders of jquery's JSON parsing capabilities

Having trouble parsing the JSON data that is out of my control. Can anyone help me figure out what I'm doing wrong here? data.json { "img": "img1.jpg", "img": "img2.jpg", "size": [52, 97] } { "img": "img3.jpg", "img": "img4.jpg", "size ...

Display a particular frame upon the initial loading of a Lottie animation

I've successfully integrated a lottie animation into my code. On the initial load, I'd like to display a specific frame. When the user hovers over it, I want the animation to start from the beginning and play through in its entirety. Here's ...

Ways to identify if a resize event was caused by the soft keyboard in a mobile browser

Many have debated the soft keyboard, but I am still searching for a suitable solution to my issue. I currently have a resize function like: $(window).resize(function() { ///do stuff }); My goal is to execute the 'stuff' in that function on ...

How to eliminate padding between Bootstrap col-xx columns

When using Bootstrap's col-xx classes, the padding can sometimes result in wasted space on smaller screens. To address this, I have decided to remove the padding by nesting col-xx with specific CSS settings like shown below: <style> div[class^= ...