Conceal list items by clicking elsewhere on the page

Currently, I am facing an issue with my search user functionality. Whenever a user clicks anywhere else on the page, the list of results does not disappear unless the user manually deletes all the words they have typed. This behavior is not ideal and despite numerous attempts to fix it, the problem persists. The div containing the list remains visible no matter where one clicks on the page.

$(document).ready(function(e) {
  var start = /@/ig;
  var word = /@(\w+)/ig;
  var $contentbox = $('#contentbox'),
    $display = $('#display');

  $contentbox.on('keyup', function(e) {
    var target = e.target;
    var $box = $(this),
      content = $box.text(),
      go = content.match(start),
      name = content.match(word);

    len = $.trim($contentbox.text()).length;

    if (!$(target).is('#display') && !$(target).parents().is('#display')) {
      $('#display').hide();
    }

    if (go && go.length) {
      $display.slideUp('show');
      if (name && name.length) {
        var html = '<ul class="tg_1"><li><p>test 1</p></li></ul><ul class="tg_1"><li><p>test 1</p></li></ul>';
        $display1.html(html).show();
      }
      console.log(go.length);
    }

    return false;
  });

  $(document).on("click", ".addname", function() {
    var username = $(this).attr('title');
    var old = $("#contentbox").html();
    var content = old.replace(word, "");
    $("#contentbox").html(content);
    var E = username;
    $("#contentbox").append(E);
    $("#display").hide();
    $("#contentbox").focus();
  });
});
.st_n_ar>form {
  position: relative;
}

#display_co,
#display {
  position: absolute;
  width: 98%;
  background-color: #fff;
  padding: 10px;
  left: 6px;
  top: 123px;
  display: none;
  z-index: 99;
}

.st_n_ar>form>#contentbox {
  width: 98%;
  height: 81px;
  margin: auto;
  background-color: #efefef;
  padding: 15px 12px;
  padding-bottom: 45px;
  overflow: auto;
  margin-bottom: 40px !important;
}

.st_n_ar>form>#sb_art {
  position: absolute;
  right: 6px;
  bottom: -35px;
  background-color: #0d1927;
  border: none;
  height: 35px;
  line-height: 35px;
  text-transform: uppercase;
  font-size: 12px;
  color: #fff;
  padding: 0 15px;
  transition: ease-in-out all .5s;
  -webkit-transition: ease-in-out all .5s;
  -moz-transiotion: ease-in-out all .5s;
  cursor: pointer;
}

ul.tg_1 {
  padding-left: 0;
  list-style-type: none;
  overflow: hidden;
  margin: 0;
}

.tg_1>li {
  margin: 5px auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="st_n_ar">
  <form method="POST" action="" id="postform" enctype="multipart/form-data" onsubmit="return false;">
    <div id='display'></div>
    <div id='display_co'></div>
    <div id="contentbox" contenteditable="true" name="post_dt" max="200">
    </div>

    <input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
  </form>
</div>

Jquery Fiddle Demo

Answer №1

Have you been searching for this information?

$(document).mouseup(function(e) {
    var container = $("#contentbox");

    // Check if the click target is not the container or its descendant
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        $('#display').html('').hide(); // Hide the result div block
        $("#contentbox").text(''); // Clear the field
    }
});

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

The controller in AngularJS fails to function properly after the initial page refresh

I am currently utilizing AngularJS in my hybrid Ionic application. Here is my controller: .controller('SubmitCtrl', function($scope) { console.log("It only works when the page is refreshed!"); }); The console.log function runs perfectly fine ...

Customize Typography style variations in Material-UI version 5

I have encountered a similar issue, but with a twist from Can't override root styles of Typography from Materil-UI Back in v4, I had a theme set up like this: import { createTheme } from '@material-ui/core/styles'; export const theme = cre ...

CSS: Struggling to properly position two flex items

I'm having some trouble with the alignment in my flex container. The title is perfectly centered, but the breadcrumb content is not aligning correctly. Specifically, I want the breadcrumbs to be right-aligned and positioned 25px from the top within t ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

When using Express, the XML response is returning an empty document

I'm experimenting with a simple API that returns XML response: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const libxmljs = require("libxmljs"); const PO ...

Text displayed in a pop-up when hovering

I'm in search of suggestions for creating a text pop-up that displays when the mouse hovers over specific text. After researching numerous websites, I haven't found exactly what I need. Currently, I have a table with headers at the top and I woul ...

An HTML/CSS component that dynamically adjusts its height at random intervals

My goal is to have the footer of my page occupy just one line in height. On occasion, when I open my page in a new browser tab, the footer ends up being two lines tall. However, if I simply reload the page within the same tab, everything appears as intende ...

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

Obtaining data from a CSV file and transforming it into JSON format results in an array

Currently, I am working on a function that takes a JSON object and prints it out as strings: GetAllArticles: (req, res) => { var allArticles = getAllArticles(); res.setHeader("Content-Type", 'application/json'); res.w ...

Tips on changing rows within tables using HTML code

I have a code snippet that pulls data from a database and displays it in a table format. However, I am facing an issue where courses with the same term number are being displayed on separate rows. Here is the current code: <html> <head> <ti ...

What is the reason behind JavaScript's restriction on using double comparison operators?

What is the reason behind javaScript not supporting double comparison? For example, in 64 < str.charCodeAt(i) && str.charCodeAt(i)<=77, why is it not possible to simplify it to 64 < str.charCodeAt(i)<=77? ...

The scrolltop function is dysfunctional on CentOS operating systems

I'm currently working on implementing smooth scrolling functionality when a button is clicked. The feature works perfectly fine with a local Apache server and IE10+, but when the project is deployed on "CentOS", it doesn't work on the same browse ...

Issue encountered while configuring input in ReactJS: the label is conflicting with the input value, causing it to be overwritten when using material.ui components

Hello fellow developers! I am currently facing an issue in my reactJS project. I am using the react-form-hook along with Material-UI's TextField. The problem arises when I input data into a field named cep, triggering a function that fetches content ...

Guide to incorporating a scroll-follow effect in multiple directions

I am facing a challenge with managing an array of divs that exceed the dimensions of their container. I have set overflow to hidden on the container and used JQuery Overscroll to achieve an iPhone-like scrolling effect on the map. The problem I'm try ...

Using the useState hook in a loop can sometimes result in a unique key error

Trying to add multiple items for rendering in my browser, but encountering an issue after clicking addItem. The item does render, however, I am getting the following error message: 'Warning: Each child in a list should have a unique ""key"" ...

Changing a background image url using jQuery by clicking a button

I'm struggling to find a way to use jQuery to add a background image URL to my CSS. Everything I've attempted so far has been unsuccessful. let button = document.querySelector('form button.btn') button.addEventListener('click&ap ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...

Guide to placing a heading in one corner and a button in the opposite corner

Desired Outcome: I am aiming to achieve a design similar to the one shown in the image below. https://i.sstatic.net/7AbdL.png Actual Result: However, what I ended up with looks more like the image below. https://i.sstatic.net/nrQZf.png This is my HTML: & ...

Guide on creating a square within an element using JavaScript

After conducting thorough research, I find myself unsure of the best course of action. My situation involves a Kendo Grid (table) with 3 rows and 3 columns. Initially, the table displays only the first column, populated upon the page's initial load. S ...

Populating dependent dropdown menus with database values while in edit mode

I'm struggling with filling dependent dropdowns. The dependent dropdowns work fine when entering data - I select a State from the dropdown and the dependent dropdowns reload based on that selection. The issue arises when I try to edit information. Th ...