*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.
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.
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.
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.
ready( handler )Returns: jQuery. Description: Specify a function to execute when the DOM is fully loaded.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With