Search code examples
javascriptjquerycsstooltip

trigger tooltip on button based on search field value


I want to show a tooltip on the button as long as the search field is empty.

what I have tried:

// 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 problem with this implementation is it works only the first time. I mean, if I write something in the search field and hover over the button the tooltip is not visible and that is what I want. but the problem is If I make the search field empty and hover over the button, the tooltip is not visible.

so, it works only the first time. how can I fix it?


Solution

  • You can initialize your tipso plugin on page load. Then , you can simply use tipso('show') or tipso('hide') depending on the condition to hide/show tooltip .

    Demo Code :

    $(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>