Search code examples
javascriptjqueryhtmlbackgrounddocument-body

Changing the background color and opacity of the body behind a toggle


I posted this question (jQuery/JavaScript if statement for two toggles) yesterday where I wanted to prevent the user from opening two toggles at the same time. From some user's advice I got the result that I was looking for with the following code:

$(document).ready(function() {
  $('.toggle-1').click(function() {
    if ($('.toggle-2').hasClass('active')) {
      // remove toggle-2 active classes
      $('.toggle-2').removeClass('active');
      $('.toggle-2-content').removeClass('active');
    }

    $('.toggle-1').toggleClass('active');
    $('.toggle-1-content').toggleClass('active');
  });

  $('.toggle-2').click(function() {
    if ($('.toggle-1').hasClass('active')) {
      // remove toggle-1 active classes
      $('.toggle-1').removeClass('active');
      $('.toggle-1-content').removeClass('active');
    }

    $('.toggle-2').toggleClass('active');
    $('.toggle-2-content').toggleClass('active');
  });
});

Now I am trying to inable the user to scroll in the background, set a different background color and opacity behind the active toggle and I am not succeeding in doing so by adding the following piece of code:

                                    $('body').css({
  overflow: 'hidden',
  background-color: 'black',
  opacity: '0.5'
 });

The way I insert the new code in the code above is the following:

$(document).ready(function() {
  $('.toggle-1').click(function() {
    if ($('.toggle-2').hasClass('active')) {
      // remove toggle-2 active classes
      $('.toggle-2').removeClass('active');
            $('.toggle-2-content').removeClass('active');
    }

    $('.toggle-1').toggleClass('active');
    $('.toggle-1-content').toggleClass('active');


    $('body').css({
      overflow: 'hidden',
      background-color: 'black',
      opacity: '0.5'
     });
  });



  $('.toggle-2').click(function() {
    if ($('.toggle-1').hasClass('active')) {
      // remove toggle-1 active classes
      $('.toggle-1').removeClass('active');
            $('.toggle-1-content').removeClass('active');
    }

    $('.toggle-2').toggleClass('active');
    $('.toggle-2-content').toggleClass('active');
  });
});

Now the toggles do not even work. I'd really appreciate if someone could tell me what I have done wrong.

Thanks in advance for your help!


Solution

  • This is because the dash of background-color, it's invalid for js to put dash in the variable. (it will be interpreted as a subtract operator)

    try

    $('body').css({
          overflow: 'hidden',
          'background-color': 'black',
          opacity: '0.5'
    });
    

    or

    $('body').css({
          overflow: 'hidden',
          backgroundColor: 'black', // this is valid in jQuery css function
          opacity: '0.5'
    });