Sqnkov Sqnkov - 1 month ago 8
Javascript Question

Toggle .dimBackground() method on click

I am trying to dim the background of my main content while accenting on a sidebar that needs to show up from the right, so I am using the dim-background jquery plugin. I want to toggle the

.dimBackground()
method for my element when I click its trigger. It adds a div with the class of
dimbackground-curtain
and it simply stacks this div when I click the trigger, making everything darker and darker.

I want to be able to toggle both the sidebar and the dimming above the main content. And if possible, to be able to toggle it if I click outside the sidebar as well.

Sample code from the fiddle:

$('.trigger').click(function() {
$('.sidebox').toggleClass('sidebox-open');
$('.sidebox').dimBackground({
darkness: 0.35
});
});


There is no CDN that provides this library, however, here is the Fiddle describing my problem.

Answer

According to the Usage guide, there's a .undim method. It seems that .dimBackground does not toggle, so you will have to store the state on your end and invoke either .dimBackground or .undim depending on the state and switch it.

Example:

var dimmed = false;
$('.trigger').click(function() {
  var $sidebox = $('.sidebox'); //avoid searching the element twice
  if(dimmed){
      $sidebox.removeClass('sidebox-open');
      $sidebox.undim();
      dimmed = false;
  } else {
      $sidebox.addClass('sidebox-open');
      $sidebox.dimBackground({
        darkness: 0.35
      });
      dimmed = true;
  }
});