Search code examples
javascripthtmlcssprintingmedia-queries

Using media queries in JavaScript or if/else statements in CSS


I am building a webpage with a customisable print settings.What happens is that whenever the print button is clicked, a dialog box is opened (I did with the onclick attribute and some js). The dialog box has some checkboxes, which are named as follows:

  • Remove Menu
  • Remove sidebars
  • Remove links and buttons
  • Remove comments

So, what I want is, whenever a user clicks the checkboxes, the linked items are removed from the @media print queries.

So, the ways I can think of is to use media queries in JavaScript or conditional statements in css.

Is it possible or some other language is required?


Solution

  • What I would recommend instead is adding/removing classes to the items, and including them in your print CSS. Could be as simple as:

    .hidden {
      display: none;
    }
    

    Then, in your JavaScript:

    document.querySelector('.comments').classList.add('hidden');
    

    See also: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList