Adding a zoom attr to a container I have two buttons, + and -, to add a zoom attr to a container. I'm not sure how I can rewrite this in fewer line of code.

jsFiddle

var ZOOM_OFFSET = 20;
var MAX_ZOOM = 60;
var MIN_ZOOM = 0;

$('.schedule-zoom .zoom-btn:not(.disable)').click(function(){
  var action_button = $(this);
  var zoom_out_button = $('.schedule-zoom .zoom-out');
  var zoom_in_button = $('.schedule-zoom .zoom-in');

  var container = $('.fixed-container');
  if (container.attr("zoom") === undefined) {
    container.attr("zoom", 0);
  }
  var zoom_value = parseInt(container.attr("zoom"));

  if (action_button.hasClass("zoom-in")) {
    zoom_out_button.removeClass("disable");

    if(zoom_value &lt; MAX_ZOOM) {
      container.attr("zoom", zoom_value + ZOOM_OFFSET);
    } else {
      action_button.addClass("disable");
    }
  }

  else if (action_button.hasClass("zoom-out")) {

    zoom_in_button.removeClass("disable");
    if(zoom_value &gt; MIN_ZOOM) {
      container.attr("zoom", zoom_value - ZOOM_OFFSET);
    } else {
      action_button.addClass("disable");
    }
  }

  container.html(container.attr("zoom"));


});


&lt;div class="fixed-container"&gt;
    0
&lt;/div&gt;

&lt;div class="schedule-zoom"&gt;
    &lt;button class="zoom-btn zoom-in"&gt;+&lt;/button&gt;
    &lt;button class="zoom-btn zoom-out"&gt;-&lt;/button&gt;
&lt;/div&gt;
Let's remove all if/else checks:


Set direction to 1 or -1 based on the button class and multiply it by ZOOM_OFFSET
Use Math.max, Math.min to constrain zoom value in the range
Use .toggleClass('.foo', condition) to disable the buttons conditionally
Set the attribute just once, in the end: no need to treat the absence of the attribute specially, just use a fallback parseInt(foo) || MIN_ZOOM


And fix some inconsistencies:


Use camelCase names for normal variables, which is a standard JavaScript convention
Use single or double quotes for strings consistently
Prefer .text(foo) over .html(foo) in case of a simple text without HTML tags




$('.schedule-zoom .zoom-btn:not(.disable)').click(function() {
  var direction = $(this).hasClass('zoom-in') ? 1 : -1;
  var container = $('.fixed-container');

  var zoom = parseInt(container.attr('zoom')) || MIN_ZOOM;
  zoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom + direction * ZOOM_OFFSET));

  container.attr('zoom', zoom).text(zoom);
  $('.schedule-zoom .zoom-in').toggleClass('disable', zoom == MAX_ZOOM);
  $('.schedule-zoom .zoom-out').toggleClass('disable', zoom == MIN_ZOOM);
});