Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Run JavaScript function immediately and in eventListener

I have a function which must be executed immediately then in an eventListener.

Here is how I run both:

function mediaBodyClass() {

    var body = document.body;

    if (window.innerWidth >= 992) {
        body.classList.add('desktop');
        body.classList.remove('mobile');
    } else {
        body.classList.add('mobile');
        body.classList.remove('desktop');
    }

};

mediaBodyClass(); // Now

// In the listener
window.addEventListener('resize', function() {
    mediaBodyClass();
});

What is the best practice?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use a media query to apply styles to the body when the screen width is smaller than a certain limit, instead of using JavaScript:

body{
    /* .desktop styles go here */
}

@media only screen and (max-width: 992px) {
  body {
    /* .mobile styles go here  */
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

Whilst what you are doing is fine - you might find the matchMedia api useful - basically its a javascript version of a media query in which you can attach functions to given viewport widths and also listen for changes to the viewport size.

Here is a link to a useful article.https://css-tricks.com/working-with-javascript-media-queries/

const mediaQuery = window.matchMedia('(min-width: 992px)')

function handleViewportSizeChange(e) {
 var body = document.body;
  if (e.matches) {
    body.classList.add('desktop');
    body.classList.remove('mobile');
  }else {
    body.classList.add('mobile');
    body.classList.remove('desktop');
  }
  
}

// Register event listener
mediaQuery.addListener(handleViewportSizeChange)

// Initial check
handleViewportSizeChange(mediaQuery)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!