Build a Time (Hours,Minutes and Seconds) Unit Converter in Browser Using Vanilla Javascript Full Project For Beginners

Build a Time (Hours,Minutes and Seconds) Unit Converter in Browser Using Vanilla Javascript Full Project For Beginners

 

Welcome folks today in this blog post we will be building a time (hours,minutes and seconds) unit converter in browser using vanilla javascript. All the full source code of the application is shown below.

 

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

<p><input type="number" id="time"><p>
<p>
  <button id="sec2min">Sec2Min</button><br>
  <button id="min2hour">Min2Hour</button><br>
  <button id="sec2hour">Sec2Hour</button><br>
</p>
<p>
  <pre type="text" id="result">Result</pre>
</p>

 

 

And now make a script.js file and copy paste the following code

 

 

script.js

 

 

(function (global) {
  var TimeConvert = (function () {
    function TimeConvert() {}
    
    TimeConvert.prototype.sec2min = function (time) {
      var min = Math.floor(time / 60);
      var sec = time % 60;
      
      return {
        min: min,
        sec: sec
      }
    }
    
    TimeConvert.prototype.min2hour = function (time) {
      var hour = Math.floor(time / 60);
      var min = time % 60;
      
      return {
        hour: hour,
        min:min
      }
    }
    
    TimeConvert.prototype.sec2hour = function (time) {
      var sec = (time % 60) % 60;
      var min = Math.floor(time / 60) % 60;
      var hour = Math.floor(time / 3600);
      
      return {
        hour: hour,
        min: min,
        sec: sec
      }
    }
    
    return TimeConvert;
  })();
  
  global.TimeConvert = TimeConvert;
}(this));

window.onload = function () {
  var timeConvert = new TimeConvert();
  var result = document.getElementById('result');
  var buttons = document.getElementsByTagName('button');
  var button;
  for (var i=0; i<buttons.length; i++) {
    button = buttons[i];
    button.addEventListener('click', function () {
      var time = document.getElementById('time').value;
      var method = this.id;
      switch (method) {
        case 'sec2min':
          result.innerText = JSON.stringify(timeConvert.sec2min(time));
          break;
        case 'min2hour':
          result.innerText = JSON.stringify(timeConvert.min2hour(time));
          break;
        case 'sec2hour':
          result.innerText = JSON.stringify(timeConvert.sec2hour(time));
          break;
      }
        
          
    });
  }
}

 

See also  Node.js Project to Find Facebook Page ID from Page Name Using page-id-of Library in Javascript

 

 

And now if you open the index.html file inside the browser you will see the below screenshot

 

 

Leave a Reply