In JavaScript, a dropdown menu becomes active when clicked on and becomes inactive when clicking outside of it

My script is not functioning properly when I click outside of the drop-down menu of the "Sign in" button.

View jsfiddle Demo

$(document).ready(function() {
  $(".openmenu").click(function() {
    var X = $(this).attr('id');
    if (X == 1) {
      $(".submenu").hide();
      $(this).attr('id', '0');
    } else {
      $(".submenu").show();
      $(this).attr('id', '1');
    }
  });
  $(".submenu").mouseup(function() {
    return false
  });
  $(".openmenu").mouseup(function() {
    return false
  });
  $(document).mouseup(function() {
    $(".submenu").hide();
    $(".openmenu").attr('id', '');
  });
});

$(document).ready(function() {
  myInit()
})
/* CSS Styles */ 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-bar">
  <div id="top-bar-inner">
    <div class="right">
      <ul>
        <li><a href="/">Register</a>
        </li>
        <li><a href="#" class="openmenu">Sign In</a>
        </li>
        <div class="submenu" style="display: none;">
          <p>test</p>
        </div>
      </ul>
    </div>
    <div class="clear"></div>
  </div>
</div>

When I click on the "Sign in" button, it adds the active class which changes the background color of the button. However, this functionality does not work when clicking outside the button. I want the active class to be removed and the original CSS colors to return. What am I doing wrong?

Answer №1

Make sure to include the following code snippet inside your mouseup event:

.removeClass("active");

right after

$(".openmenu").attr('id', '');

so it looks like this:

$(document).mouseup(function(){
   $(".submenu").hide();
   $(".openmenu").attr('id', '').removeClass("active"); <-----
});

FIDDLE

Also, remember to select jquery from the side menu when using jsFiddle instead of copying the library into the fiddle.

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

Achieving sequential actions in Javascript without the need for state updates

One aspect of jQuery that I find impressive is its ability to chain methods like .animate() and .css(). This is made possible by utilizing the special variable "this" in the backend code. I am interested in implementing a similar method chaining mechanism ...

Create a React application that features a countdown timer using the new Date()

I have attempted to create a countdown timer, but I am encountering a problem with the getTime() function. This function calculates the remaining time by subtracting the current time from the finish time. However, the function is called multiple times ever ...

Tips on how to properly display the date in v-Calendar

I'm struggling to format the date output from the v-calendar. Currently, it appears like: Fri Jul 31 2020 00:00:00 GMT+0200 (utc summertime) However, I would like it to display as 2020-07-28. I have searched through the documentation but couldn' ...

Adding images to .xsl using XML

I have created a unique "blog" using XML and XLST. The format of the blog is as follows: <post id="1" category="Miscellaneous"> <ptitle>MiG-21</ptitle> <psubtitle>Mikoyan-Gurevich MiG-21</psubtitle> <image></image& ...

Customizing Attribute for Material UI TextField

I'm currently in the process of adding a custom data attribute to a TextField component like so: class TestTextField extends React.Component { componentDidMount() {console.log(this._input)} render() { return ( <TextField label= ...

Slide one div up when another div is hovered over

I have a block named case-card with a child division called case-card__wrapper that contains text. When hovering over the case-card, I would like the case-card__wrapper to subtly move upwards in a transition, rather than abruptly jumping from one position ...

Do JavaScript Promises operate asynchronously?

Can we clarify if JavaScript Promise is asynchronous? I've been researching Promise and async programming, particularly with ajax requests. If Promise isn't inherently async, how can we make it so? For instance, consider a function that encapsul ...

Struggling to create HTML divs with CSS styling

Currently working on creating a 768x240 window design. An example of what I have so far: <div class="global-tab"> <div class="image" src="link"></div> <div class="class1">{{details.name}}</div> <div class="class2" ...

Prevent certain HTML content from being displayed in the input field

My input field behaves like a chat box where users can enter text that gets displayed on the page. However, I've discovered that users can also include HTML tags in their inputs to manipulate the output. For example, entering <b>Hello</b> ...

Inspect each page to confirm that the user has verified that they are of legal age

I'm currently developing a website (tobacco-related) that imposes an age validation requirement on all visitors before granting access to the site. I've implemented a form for age verification, but I'm stuck at how to store a cookie upon pas ...

Exploring the power of Sitecore in combination with Solr search functionality and Autos

We've integrated Solr Search with Sitecore 8.1 and MVC, but we're encountering difficulties with the Auto complete/Auto Suggestion feature in the search text box. Challenge: The search results are not displaying as quickly as expected, leading t ...

Activate the jquery floatlabels plugin when the input is loaded

I'm currently experimenting with the jquery floatlabels plugin to implement inline labels for input fields in a form. The plugin works perfectly for fields without any text, but I need the label to display even if there is default text present. Upon ...

Dealing with errors in jQuery when handling JSON

Currently, I am utilizing jQuery's ajax feature to transmit JSON to a PHP script and then acquire a JSON set of values for processing on the front end. The PHP script is properly sending the JSON data, and I am successfully able to display the JSON o ...

Creating vibrant row displays in Vue.js: A guide to styling each row uniquely

I am not a front-end developer, so Vue and JS are new concepts for me. Currently, I am working on an application for managing sales. One of the components in my project involves displaying invoices in a list format. To make the rows visually appealing, I ...

js-libp2p works by establishing connections between nodes without initiating a new stream

To access the complete source code, visit this link: https://github.com/Gbr22/p2ptunnel listener: $ node listener.js The listener is ready and actively listening on: /ip4/192.168.0.101/tcp/10333/p2p/QmcrQZ6RJdpYuGvZqD5QEHAv6qX4BrQLJLQPQUrTrzdcgm /ip4/1 ...

Ensure that the fixed header's width matches the size of the container div

The header element is contained within a div. I have positioned the header as fixed, leading to 2 issues: The width of the header extends beyond the width of the div container. It should align with the div. When the header is fixed, the other elements li ...

Fetching an array through an AJAX request that triggers a PHP script

Currently, I am working on a project where I need to automatically fill a textbox by utilizing AJAX to fetch data from a PHP script that triggers a C function. In theory, this is what I have come up with: (Assuming single value reception) $(document).re ...

Utilizing AngularJS to access the corresponding controller from a directive

When I have HTML structured like this... <div ng-app="myApp"> <div ng-controller="inControl"> I enjoy sipping on {{beverage}}<br> <input my-dir ng-model="beverage"></input> </div> </div> a ...

The web application encountered an error: "Uncaught TypeError: Cannot read property 'map' of undefined" when trying to retrieve

Struggling with a simple API fetch, and despite checking everything multiple times, I can't seem to figure out what's going wrong. It feels like I'm missing something crucial. import { useState } from "react"; import ProductCard fr ...

Sending an assurance via Nodemailer and returning a promise using Fetch

I'm encountering an issue where the code inside a .then() is not running after a successful resolution of a fetch() POST method. It only seems to run if the fetch rejects. The scenario involves sending an email using Nodemailer via my server. I suspec ...