skip to Main Content

I have the following code, which loads div#b into div#a and subsequently does something with div#b:

<html>
    <head>
      <script src="scripts/jquery.js"></script>
    </head>
    <body>
        <script>
            document.addEventListener('DOMContentLoaded', e => {
                $('#a').load('test2.html', {},
                    // function() {
                        // console.log($('#b').attr('id')); // returns "b"
                        // $('#b').html('content in #b');
                        // console.log('completed');
                    // }
                    fillB()
                );
            });
            function fillB(option=null) {
                console.log($('#b').attr('id'));//returns undefined :(
                $('#b').html('content in #b: '+option);
                console.log('completed');
            }
        </script>
        <div id="a">placeholder</div>
    </body>
</html>

where test2.html contains:

<div id="b"></div>

My objective is to have the callback function (commented out) be a named function fillB() instead, so that I can reuse the code elsewhere. However, when I do this, the selector $(‘#b’) returns undefined.
How can I have the function fillB() execute the selector correctly, when it is called?

Edit: I also want to be able to control what parameters are passed to fillB().

2

Answers


  1. Chosen as BEST ANSWER

    Apparently I have to pass the named callback function in an anonymous one:

    function() { fillB(); }
    

  2. You can do this instead. It is much shorter and does the same with fewer places to go wrong

    I also changed the vanilla load event to a jQuery one

    const fillB = () => {
      $('#b').html('content in #b');
    };
    
    $(function() {
      $('#a').load('test2.html', fillB);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search