Create A Photoshop Like Ruler With jQuery - Ruler.js

File Size: 7.24 KB
Views Total: 2179
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Create A Photoshop Like Ruler With jQuery - Ruler.js

A small jQuery script that helps web developers create a responsive, Photoshop-like ruler placed on the x-axis, with ticks every 5 pixels and markings every 50 pixels.

How to use it:

1. Create a container to hold the ruler.

<div class="ruler"></div>

2. Include the needed jQuery library (slim build) at the bottom of the webpage.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous"></script>

3. The main JavaScript (script) to create a ruler.

function createRuler() {
  var $ruler = $('.ruler');
  for (var i = 0, step = 0; i < $ruler.innerWidth() / 5; i++, step++) {
      var $tick = $('<div>');
      if (step == 0) {
          $tick.addClass('tickLabel').html(i * 5) ;
      } else if ([1, 3, 5, 7, 9].indexOf(step) > -1) {
          $tick.addClass('tickMinor');
          if (step == 9) {
              step = -1;
          }
      } else {
          $tick.addClass('tickMajor');
      }
      $ruler.append($tick);
  }
}

4. Render the ruler inside the container element you just created. Don't forget bind the createRuler function to the window.resize event so the ruler is always spannning the full width of container.

$(window).on('load resize', function() {
  $('.ruler').empty();
  createRuler(); 
});

5. The CSS to style the ruler. Feel free to modify or override the following CSS snippets to create your own styles.

.ruler {
  position: absolute;
  top:0; left:0;
  width: 100%; height: 25px;
  background: #eee; color: #000;
  font-family: arial;
  font-size: 12px; line-height: 14px;
  border-bottom: 1px solid;
  overflow: hidden;
  z-index: 9;
}

.ruler > div {
  display: inline-block;
  background: #000;
}

.ruler .tickLabel {
  position:relative;
  top: -10px;
  margin-left: 4px;
  width: 1px;
  height: 100%;
  text-indent: 1px;
  line-height: 20px;
}

.ruler .tickLabel:first-of-type {
  margin-left: 0px;
}

.ruler .tickMajor {
  margin-top: 19px;
  margin-left: 4px;
  width: 1px;
  height: 6px;
}

.ruler .tickMinor {
  margin-left: 4px;
  width: 1px;
  height: 4px;
}

This awesome jQuery plugin is developed by michaelsboost. For more Advanced Usages, please check the demo page or visit the official website.