-1

I have a responsive panel that changes based on the width of the web browser. Based on the number of list items I want a block to be displayed. For instance, if there are two list items I want the block to be displayed at window width of 500px.

My question is: What would be the best and most optimized method for doing this?

Current code to get number of list items in ul:

document.querySelectorAll("#ulClass li").length

My current thought is to use a switch on a window resize event:

window.addEventListener('resize', function(event){
  // do stuff here
});

Note:

  1. I need to use plain JavaScript, no plug-ins, etc.
  2. I can't use Resize Observer.
DaveJones
  • 75
  • 8
  • We can use css media queries instead of javascript. Is there any limitation of media query you are facing ? – Priyanka Nov 19 '19 at 10:15
  • Use the resize function a you mentioned, but implement a timeout. That what you dont need massive computing. –  Nov 19 '19 at 10:16
  • @Niklas That sounds like a great idea. Can you point me in the direction of what I should look for in order to implement a timeout? – DaveJones Nov 19 '19 at 10:16
  • @Priyanka Thanks for the suggestion, however I can't change the layout using media queries as they can't work in correspondence with the unknown number or list items. Do you mean something along the lines of: https://stackoverflow.com/questions/5489946/how-to-wait-for-the-end-of-resize-event-and-only-then-perform-an-action – DaveJones Nov 19 '19 at 10:18
  • I think still I haven't got your question. Will be helpfull if you explain with example or codepen link. May be I can help you with better solution – Priyanka Nov 19 '19 at 10:24

1 Answers1

1

If you need to use JS: 1) Make an event listener that will react everytime you resize the browser like:

window.addEventListener('resize', function(event){

});

2) Create a function that will be fired every time user resizes the window

function handleResize(){

}

3) Call that function in your eventListener like so :

 window.addEventListener('resize', function(event){
      handleResize();
    });

4) create a variable that will store the list of your list items like:

  const items = document.querySelectorAll(".some-list");

5) get the width of the screen -> https://www.w3schools.com/js/js_window_screen.asp

5) inside your handleResize function - check the width of the screen and based on that + based on the numbers of the elements - add a particular css class like

.visible {
dsiplay:block;
}
AdamKniec
  • 1,607
  • 9
  • 25