Activate a tooltip on the button depending on the value entered in the search field

I need to display a tooltip on the button when the search field is empty.

Here is what I have attempted:

// Enable hover feature
const searchBtn = document.querySelector('.find__btn');

searchBtn.addEventListener('mouseover', () => {
  const searchText = document.querySelector('.find__field');
  console.log(searchText.value);
  if (searchText.value.length === 0) {
    jQuery(searchBtn).tipso({
      titleContent: 'Hello',
    });
  }
});

The issue with this approach is that it only works the first time. If I type something in the search field and then hover over the button, the tooltip does not appear as expected. However, if I subsequently clear the search field and hover over the button again, the tooltip still does not show up.

So, it seems to work only the first time. How can I resolve this?

Answer №1

If you want to set up the tipso plugin when the page loads, you can do so easily. Then, simply utilize tipso('show') or tipso('hide') based on the condition for displaying or hiding the tooltip.

Check out this Code Demo :

$(function() {
  var searchBtn = jQuery('.find__btn');
  searchBtn.tipso({
    titleContent: 'Hello',
  });
  searchBtn.on("mouseover", function() {
    var searchText = $('.find__field').val();
    if (searchText.length === 0) {
      searchBtn.tipso('show'); //show 
    } else {
      searchBtn.tipso('hide'); //hide..
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tipso/1.0.8/tipso.css" integrity="sha512-huSVDpZEo5Zb91YBqN03p+XP7b2S8m9nB/Pn2rbwOe0GF+jvPaFx06mexoH8lAmpa4+OEe1G4Wp3UGYcrY8V1g==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tipso/1.0.8/tipso.min.js" integrity="sha512-uffeXd+Tch3d7SWCkqqRg56IiDLYVnsXSJ22uDJ5DP1Nh55XphpL1BHL4c2NbpBrgmPjH4w9C9zgYQzwC8343w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<input type="text" class="find__field">
<button class="find__btn">Find..
</button>

Answer №2

In my opinion, it would be more effective to assess the content of the textbox to trigger the tooltip's display.

Below is a snippet of code that demonstrates this concept:

function checkTextbox(element)
{
    let tooltip = document.getElementsByClassName("tooltiptext")[0];
    let visibleClass = 'visible';
    if(element?.value?.length === 0)
      tooltip?.classList.add(visibleClass);
    else
      tooltip?.classList.remove(visibleClass);      
}
/* Tooltip container */
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}

/* Tooltip text styles */
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  /* Position the tooltip text */
  position: absolute;
  z-index: 1;
  top: 0;
  left: 160px;
  margin-left: -60px;

  /* Fade in tooltip effect */
  opacity: 0;
  transition: opacity 0.3s;
}

/* Tooltip arrow design */
.tooltip .tooltiptext::after {
  content: "";
  position: absolute;
  top: 0%;
  left: 0%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: #555 transparent transparent transparent;
}

/* Show the tooltip text on hover */
.tooltip:hover .tooltiptext.visible {
  visibility: visible;
  opacity: 1;
}
<input type="text" placeholder="Type something" onchange="checkTextbox(this)"/>
<button class="tooltip" >
  Go!
  <span class="tooltiptext visible">Oops! Something missing!</span>
</button>

If you plan to utilize jQuery Tipso, consider storing a variable indicating whether the textbox is empty before accessing it within your mouseover function.

Please note: The CSS styling for the tooltip was sourced from https://www.w3schools.com/howto/howto_css_tooltip.asp

Best regards!

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

Conceal an element following the .load() function

I am currently working on creating a login popup with the goal of allowing users to login without the need for a page refresh. Once a user logs in, I refresh my page using the following code: $('body').find('#wrap').load(window.locatio ...

"Utilizing Bootstrap to ensure content is aligned perfectly to the baseline

I've been struggling to align my contents to the baseline while working with the bootstrap framework. I tried following the instructions in the documentation, but it didn't work out as expected. <div class="row"> <div class="col-12 ...

Tips for maintaining the functionality of IFrame?

I am encountering an issue with tracking clicks on a div that contains an IFrame. While the tracking functionality works, it seems to interfere with the IFrame's functionality. Is there a way to resolve this and make both functionalities work simultan ...

Is there a way to duplicate a specific quantity of icons with Polymer?

I am facing a bit of a challenge with a seemingly simple task. My goal is to showcase the number of credits completed by each student in my list using star icons. For instance, John ★, Sarah ★★, Ken ★, and Jared ★★★★. The JSON data contai ...

Efficiently incorporating multiple properties into one in Angular

Within my Angular service, I have defined variables in the following manner: export class MyService { someVariableA = 1; someParams = { someVariableB, otherVariable: this.someVariableA }; } In a component, I update 'someVariableA&a ...

Apply a specific class using JavaScript/jQuery when a user selects a specific timezone from the user interface

Currently, I am coding in HTML with the code below extracted from this website link. The listings under timezone ET are all correct as they align with the accurate dates; however, for other timezones (PT, MT, CT, AT, NT) some shows seem to be on incorrect ...

Discover the identity of an element through the value of another element

Looking for a way to retrieve the id value based on the input value in this HTML code. For instance, I need to identify the id value associated with the input value of number2 - which is unknown2. How can this be achieved using jQuery? <th id="unknow ...

Exploring Node troubleshooting with WebPack and Feathers

Currently, I am part of a team working on a project that involves using Node, Webpack, TypeScript, and Express/Feathers. While my fellow developers are experienced in these technologies, I have limited experience with JavaScript mainly on the client-side a ...

Flex box causing Bootstrap5 responsive table to overflow

Need help with fixing overflow issue in a fixed-width div used as a left sidebar. The main content renders correctly except for tables with many columns, causing overflow before the scroll bar appears. How can this be resolved? Various layout attempts hav ...

Encountered a network error: A rogue token < was found in JSON at position 0 within a new Apollo

https://i.sstatic.net/D25ai.png const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { ...

Pass the modified array of object properties to the front end after making necessary changes

Within my node (express) setup, I am looking to include a new property before sending my response (referred to as result in this case) to the front-end. async.parallel(stack, function (err,result) { result.users[0].price = 100 // console.log(result.us ...

Guidelines for capturing a div screenshot with javascript

Let's say I have a div containing an image source. <div> <p class="row">With custom CSS</p> <img src="/images/midhun.jpg"> </div> When a button is clicked, I want to display a screenshot of this image in another div. C ...

How can the event listener be utilized with md-autocomplete?

I am currently in the process of developing an angularjs application that incorporates an autocomplete feature. One key aspect of this application is that certain fields cannot be populated until an item has been selected using the autocomplete function. ...

The proxy encountered a TypeError when the trap for the property 'set' returned a falsish value

After migrating my code from using es5 class prototype representation to es6 class representation, I encountered an error. This is the comparison of the code before and after migration: ES5 syntax function RoutingScreen (context) { Object.assign(this, ...

Calling a function within another function is not allowed in Typescript

Essentially, I have an Angular Web Page that uploads a file to the server via a POST request, which is then received by my NodeJS app. The issue arises when attempting to retrieve the file path in subirArchivo() and pass it to a function called InsertaPer ...

Having trouble with an Unexpected identifier error when using setTimeout and animate together?

Here is my code snippet: setTimeout(function() $('.golden').animate({ opacity: "1", top: "84px" }, 'slow'); }, 1000 ); Ah, it throws an Unexpected identifier error. However, when I simplify the code like this: ...

Tips for iterating through JSON Data:

Struggling with looping through JSON data retrieved from an ashx page to add values to li's in a ul. How can I effectively loop through and extract the values from the following JSON data? The format of the returned data looks like this: {"ImageCol ...

How to traverse up to the parent element using XPath in nightwatch

Here is the structure I am dealing with: <div class="class"> <h4 class="class2"> "Condition" </h4> <div class = "click_class">Click_text </div> </div> I need to click on the element with class ="click ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...