Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS/jQuery - Better to run event handler in $(document).ready or in called function

*Note: The following question is not meant to be for people's opinion but is being asked in terms of best processing speed for the webpage, jQuery, etc.

I currently have code which follows the below "test" code format:

$(document).ready(function() {
  $('.my-class').on('click') {
    if ($('.my-class').hasClass('active') {
      $('.my-class').removeClass('active');
      return;
    }
    $('.my-class').addClass('active');
  }
});

My question is: should the event handler (not the event listener) be in the same code structure as $(document).ready();? Or should it look like this:

function toggler(obj) {    
  if ($(obj).hasClass('active') {
    $(obj).removeClass('active');
    return;
  }
  $(obj).addClass('active');
}

$(document).ready(function() {
  $('.my-class').on('click') {
    toggler(this);
  }
});

i.e. should $(document).ready(); only have the listeners which reference the handlers or should the entire action (of listening and handling) be in $(document).ready();

What is the proper way of doing this so as to maximize the usability/power of jQuery, JS, etc.

like image 797
4lackof Avatar asked Aug 04 '16 22:08

4lackof


People also ask

Is $( document .ready necessary?

No, it is not necessary. You can either put the script tag right before the body closing tag or if you are supporting IE9+ you can use native JS.

What is the purpose of this jQuery function $( document .ready function?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

Which event will help to prevent any jQuery code from running before the document is finished loading is ready )?

The Document Ready Event This is to prevent any jQuery code from running before the document is finished loading (is ready). It is good practice to wait for the document to be fully loaded and ready before working with it.

Which jQuery function can you use to execute when the document finished loading?

ready( handler )Returns: jQuery. Description: Specify a function to execute when the DOM is fully loaded.


1 Answers

I would go with the first snippet of code:

$(document).ready(function() {
  $('.my-class').on('click') {
    if ($('.my-class').hasClass('active') {
      $('.my-class').removeClass('active');
      return;
    }
    $('.my-class').addClass('active');
  }
});

You are not doing anything with the function toggler before the DOM is ready, so why define it outside.

like image 174
Sam Battat Avatar answered Sep 29 '22 13:09

Sam Battat