Conceal the div if a choice has not been made

Here's a scenario where a div appears if text is selected that is not just a space, but remains visible even after the selection is removed. Is there a way to hide the div if the selection becomes empty?

$("#actual_verse").mouseup(function() {
  var text = "";
  if (window.getSelection) {
    text = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    text = document.selection.createRange().text;
  }

  if (/\S/.test(text)) {
    // Tool Tip
    var ele = document.getElementById('tooltip');
    var sel = window.getSelection();
    var rel1 = document.createRange();
    rel1.selectNode(document.getElementById('cal1'));
    var rel2 = document.createRange();
    rel2.selectNode(document.getElementById('cal2'));

    if (!sel.isCollapsed) {
      var r = sel.getRangeAt(0).getBoundingClientRect();
      var rb1 = rel1.getBoundingClientRect();
      var rb2 = rel2.getBoundingClientRect();
      //this will place ele below the selection
      ele.style.top = (r.bottom - rb2.top) * 100 / (rb1.top - rb2.top) + 'px';
      //this will align the right edges together
      ele.style.left = (r.left - rb2.left) * 100 / (rb1.left - rb2.left) + 'px';
      //code to set content
      ele.style.display = 'block';
    }
    // End of Tool Tip
  }
});
/* Tool Kit */

#tooltip {
    position:absolute;
  display: none;
    border:grey solid 1px;
    background: #373737;
    padding: 5px;
    border-radius: 3px;
    -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* Internet Explorer/Edge */
  user-select: none;           /* Non-prefixed version, currently
                                  not supported by any browser */

}

#cal1{
    position:absolute;
    height:0px;
    width:0px;
    top:100px;
    left:100px;
    overflow:none;
    z-index:-100;
}
#cal2{
    position:absolute;
    height:0px;
    width:0px;
    top:0;
    left:0;
    overflow:none;
    z-index:-100;
}

.boxes {
  width: 15px;
  height: 15px;
  cursor: pointer;
  display: inline-block;
  margin-right: 2px;
  position: relative;
  top: 3px;
}

#blue_box {
  background: #AAF6FF;
}

#green_box {
  background: #D6FFAA;
}

#orange_box  {
  background: #FFBF98;
}

#purple_box {
  background: #D7D5FC;
}

#red_box {
  background: #FF9B9F;
}

#yellow_box {
  background: #FFF8AA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='actual_verse' class='context'>Lorem ipsum dolor sit amet, doctus expetendis no vel. At vis doming viderer prompta. Ut vis consul atomorum pericula, an sed sonet suscipit lobortis. Eos tale atqui iriure ne, eos in delenit corpora, nec laudem everti ei.</span>
<div id='cal1'>&nbsp;</div>
<div id='cal2'>&nbsp;</div>
<div id='tooltip'>
  <div id='blue_box' class='boxes' title='blue_mark'></div>
  <div id='green_box' class='boxes' title='green_mark'></div>
  <div id='yellow_box' class='boxes' title='yellow_mark'></div>
  <div id='orange_box' class='boxes' title='orange_mark'></div>
  <div id='purple_box' class='boxes' title='purple_mark'></div>
  <div id='red_box' class='boxes' title='red_mark'></div>
</div>

Answer №1

One possible solution is:

document.querySelector("#idOfDiv").style.display = /\S/.test(text) ? "block" : "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

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

Arranging ng-grid by a hidden column

Imagine having an array of objects structured like this: { name: ... age: ... dept: ... } Now, if you want to display these objects in an ng-grid with only columns for name and age, you can set it up like this: columnDefs: [{field:'name' ...

The 1.4.8 version of angular.js is throwing an error message labeled as $resource:badcfg. This error is showing up in the regular

After loading the page, Angular throws the following error: angular.js:12520 Error: [$resource:badcfg] http://errors.angularjs.org/1.4.8/$resource/badcfg?p0=query&p1=array&p2=object&p3=GET&p4=%2Fapi%2Fprospects%2Factive at Error (nativ ...

Optimal Timing for Stock Trading - Uncover the Ideal Days to Purchase and Vend Stocks

One possible solution I found was related to determining the maximum profit value. const pricesEachDay = [1,2,5,8,7,1,2,3] const mainFunction = (pricesEachDay) => { let buyPrice = pricesEachDay[0]; let bestProfit = 0; let startDay = 0; ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

"Utilizing Trackball controls, camera, and directional Light features in ThreeJS version r69

I am struggling to synchronize trackball controls and camera with the directional light. Here is my situation: I start by initializing an empty scene with a camera, lights, and controls. Then, I load a bufferGeometry obj, calculate its centroid, and adjus ...

Issue encountered during Heroku deployment: Failed to build React app. When attempting to push changes to Heroku, an unexpected end of input error was received instead of the expected result. This error occurred on an unidentified file at

Encountering a parsing error while attempting to deploy a React app on Heroku using git push heroku master. The app built successfully yesterday, but since then some media queries were added by another contributor to various .scss files. The primary error ...

There seems to be an issue with the functionality of the operators in the Calculator Javascript

I'm currently working on a Javascript calculator project for FreeCodeCamp and encountering an issue with the code. Whenever I input an operator like "-", "+", "x", etc., the numbers in the history section start repeating themselves. For example, if I ...

Verify whether the number of minutes aligns with a full hour mark (60, 120, 180, 240 minutes, etc)

Query Determine if a given number of minutes equates to an exact hour or multiple hours. Scenario I am currently working on a script where I need to ascertain whether a certain number of seconds corresponds to an hour or x hours; returning true if it doe ...

Merging HTML, CSS, and JavaScript in a single file to Generate a Bell Curve with the help of Google Charts API

I'm looking to streamline my code by combining HTML, CSS, and JS into a single HTML script for the existing "Bell Curve Using Google Charts API" project. Check out the project here I've tried putting the CSS in style tags and the JS in script t ...

Having trouble looping through Html5 canvas with JavaScript in Rails?

I am working on a rails project where I have a model called microposts: class Micropost < ActiveRecord::Base attr_accessible :content, :avatar belongs_to :user mount_uploader :avatar, ImageUploader To display the microposts, I created a partial ...

LazyTreeGrid from Dojo encounters issues with paginating children while using QueryReadStore

Currently, I am experimenting with the LazyTreeGrid implementation in Dojo and have encountered an issue. When LazyTreeGrid is paired with LazyTreeGridStoreModel and QueryReadStore for pagination of children nodes, errors sometimes arise. I attempted to l ...

Exploring different pages in an Ionic and AngularJS mobile application

I am brand new to the world of Ionic and AngularJS. I have just started working on a simple project but have hit a roadblock. My goal is, To create a login page and a register page. When a user clicks the register button on the login page, they should be ...

Issue encountered when attempting to unzip a file of size 12 megabytes

I have been using a specific open source tool to unzip files, and it works well for zips ranging from 2-5 MB. However, I encountered an error when trying to unzip a zip file that was over 10 MB in size. Are there any more reliable open source options ava ...

Tips for verifying that an input field only accepts values from an array in Angular 6

In this specific scenario, the input fields are only supposed to accept values that exist in a pre-defined array. If any other values are entered, an error should be triggered. .component.html <input type="text" ([ngModel])="InputValues& ...

DataGrid Filtering with Material-UI

I recently started working on a React project and I'm trying to incorporate the mui datagrid component. I want to include filters for '>' and '<', but I couldn't find any information in the documentation. Is there a spec ...

display files on page using express response

Is there a way to transfer files from the server for display in the browser within the index pug file? extends layout block content h1= 'saved files' #recordings.recordings.row script(src='/javascripts/listrecordings.js') functi ...

What is the most effective way to alter the elements in a JavaScript array based on the total count of another element's value?

I have a task where I need to manipulate an array by adding or removing elements based on the total count of another value. let data = [ { "details": [ { "Name": "DataSet1", "Severity": "4& ...

When using onclick="location.href='page.html'", the page fails to load on Safari browser

I've been having trouble with getting onclick="location.href='link.html'" to work and load a new page in Safari (5.0.4). In my project, I am creating a drop-down navigation menu using the <select> and <option> HTML tags. I have ...

Can you explain the meaning of the second line in the code snippet?

Could you please explain the meaning of the second line in this code snippet? Is it a ternary operation, or something else entirely? And what is its significance? const user = await User.findOne({ email: req.body.email }); !user && res.stat ...