skip to Main Content

I am tryin to call the test() function onload. This is how I am doing it:

if ($('.partical .sectionA').length) {
    test($('a.section.present'));
    $(document).ready(function(){
        test($(this));
    });
 }
test(something){...}

I find it odd to use a ready() method inside an If Else statement and I am wondering if this is a good practice or is there a better way to call the test function on page load?

All I am trying to figure out is how can I call the test function on page load only if partical sectionA is present in my html page?

2

Answers


  1. It is wrong practice. It would have to be inline before the </body> tag to even work.

    Then what is $(this) at the time of ready?

    Perhaps you mean

    $(function(){
      if ($('.partical .sectionA').length) {
        test($('a.section.present'));
      }
    });
    
    Login or Signup to reply.
  2. Since your $('.partical .sectionA') actually REQUIRES that the document should be already loaded you HAVE to put it inside ready(). So your code inside ready()‘s callback will be executed after DOMContentLoaded event and all your DOM elements will be ready for selection/manipulation:

    https://api.jquery.com/ready/

    $(document).ready(function(){
      if ($('.partical .sectionA').length) {
        test($('a.section.present'));
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search