0

I'm trying to learn jQuery and javascript so bear with me. I have a jQuery function that adds and removes classes on resize. jQuery:

 $(document).ready(function($) {
    var $window = $(window), $element = $('.test');

    function resize() {
      if ($window.width() < 768) {
        return $element.addClass('mobile');
      }    
      $element.removeClass('mobile');
    }

    $window.resize(resize).trigger('resize');
});

I would like to build this in JavaScript but am just learning it currently and am lost trying to figure that out. I'd like to see a JavaScript example but I've only found jQuery versions. I'm trying to learn the differences. An example would be greatly appreciated!

4
  • whats your problem here? Commented Mar 9, 2017 at 7:26
  • 3
    So you're saying your code works fine, you just want someone to write you the same logic in native JS, right? Also, the logic you have would be far better suited to a CSS media query as it's faster and has much less CPU overhead. Commented Mar 9, 2017 at 7:35
  • Just learn jquery - IMO it's much more efficient to develop against and much cleaner / more maintainable. If you must go with js, then there are plenty of references to convert, eg: youmightnotneedjquery.com callmenick.com/post/jquery-functions-javascript-equivalents Commented Mar 9, 2017 at 8:42
  • @freedomn-m, I see true value in learning the JavaScript that powers jQuery, and I see true value for developers wanting to learn the differences between the jQuery API and vanilla JavaScript. I agree 100% that jQuery is a super efficient tool, but jQuery is just one tool in the JavaScript developer's toolbox, so I applaud the author's desire to learn JavaScript beyond the jQuery API. Also, the author is specifically asking for us to show him the Vanilla alternative to his jQuery, so "just learn jQuery" doesn't feel relevant. Commented Mar 9, 2017 at 10:32

2 Answers 2

1

To recreate your jQuery function into a vanilla JavaScript function, you can use the following approach:

document.addEventListener("DOMContentLoaded", function(event) {
  var element = document.querySelector('.test');

  function resize() {
    if (window.innerWidth < 768) {
      element.classList.add('mobile');
    } else {
      element.classList.remove('mobile');
    }
  }
  // For performance reasons, this method should be 
  // "debounced" so that it doesn't have to execute 
  // on every resize event, only when you're done resizing.
  window.onresize = resize;
});

You can read up on debouncing and it's benefits here, or you can can check out _.debounce() from lodash.

The absolute best way (IMO) to learn the differences between jQuery and Vanilla JavaScript is to:

  • Read the jQuery source code to see how they implement their API. Because jQuery is just a JavaScript library, you can see the vanilla JavaScript that jQuery uses "behind the scenes" to make all the magic happen.
  • While you are working on a jQuery project or feature, as an exercise, try to implement the same project/feature without jQuery, you will quickly learn the reasons why jQuery is so useful, but you will learn more about the DOM and vanilla JavaScript in the browser.

Note that because this particular function is only adding and removing a class based on the window's size, you can get the same effect using @media queries in CSS, which could prove more performant than the JavaScript implementation above.

For example, you could achieve the same result without JavaScript like this:

@media screen and (max-width: 768px) {
    .test {
      background-color: red;
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

0
function ready(resize) {
  if (document.readyState != 'loading'){
    resize();
  } else {
    document.addEventListener('DOMContentLoaded', resize);
  }
}

The function above is the alternative for $(document).ready()

Your resize-function

function resize() {
  var elements = document.getElementsByClassName('test');
  var firstEl = elements[0];
  var className = 'mobile';
    if (window.innerWidth < 768) {
      // add Class
      if (firstEl.classList) {
            firstEl.classList.add(className);
        } else {
            firstEl.className += ' ' + className;
        }
      } else {
        // remove Class
        if (firstEl.classList) {
          firstEl.classList.remove(className);
        } else {
          firstEl.className = firstEl.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
        }
      } 
}

You can see that I just take the first Element that matches the className. If you want to add the class to all of the elements, loop over the Array elements.

So now we just have to add the event listener for window resize and call ready.

window.onresize = function(event) {
    resize();
};
ready(resize);

If you don't know how you can write a specific jQuery function in pure javascript I can recommend you: You Might Not Need jQuery

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.