سؤال

I want to display how much time has passed since the last time the page was reloaded.

<li id="last-update-title" onmouseover="updateTimeToolTip()">Some Text here</li>

And here is the updateTimeToolTip() function that I have

function updateTimeToolTip() {
    document.getElementById('last-update-title').title = customFormatTimeSecondsAgo(updateTime);
};

function customFormatTimeSecondsAgo(date) {
    var result = Math.floor((new Date() - date) / 1000);
    if (result <= 1) return "Updated: Just now";
    return "Updated: " + result + " seconds ago";
};

These functions working fine now to calculate the time. It displays the time passed when I hover on the text. However, the title attribute will not change while the mouse is over it which is normal but I think it would be nice if I could make it keep updating while the mouse is over the text. Is there any way I can achieve this without using any external JQuery?

Thanks

هل كانت مفيدة؟

المحلول

I wouldn't try and update the native browser tooltip if I were you, I would try something more custom like this:

  <html>
    <head>
    </head>
    <style>

      #last-update-title{
        position: relative;
        margin-top: 20px;
      }

      #tooltip{
        position: absolute;
        top: -20px;
        display:none;
      }

      #tooltip.show{
        display:inherit;
      }

    </style>
    <body>

      <div id="last-update-title" onmouseover="showToolTip('show');" onmouseout="showToolTip('');">
        Some Text here
        <div id="tooltip"></div>
      </div>

    </body>
    <script type="text/javascript">

      function showToolTip(show){
        document.getElementById('tooltip').className = show;
      }

      var startDate = new Date();
      setInterval(function(){
          document.getElementById('tooltip').innerHTML = customFormatTimeSecondsAgo(startDate);
      }, 1000)

      function customFormatTimeSecondsAgo(date) {
          var result = Math.floor((new Date() - date) / 1000);
          if (result <= 1) return "Updated: Just now";

          return "Updated: " + result + " seconds ago";
      };


    </script>
  </html>

This avoids problems around how different browsers render tooltips, and also will get around the tooltip not updating dynamically as you want it to.

نصائح أخرى

If you want to have a something that acts similar to a clock i recommend using the interval function, like so:

<li id="last-update-title" onmouseover="function(){setInterval(updateTimeToolTip(), 3000);}">Some Text here</li>

Try this.

var updateInterval;
$(function() {
    $('#last-update-title').on('mouseover', function() {
        updateInterval = setInterval(updateTimeToolTip, 10);
    });

    $('#last-update-title').on('mouseout', function() {
        clearInterval(updateInterval);
    });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top