Question

What I have is fairly standard code for using JavaScript with SharePoint 2013. Inside the sharePointReady function, I have a few dynamic controls that are added to the page.

The problem is that when I attempt to call the click function, nothing is actually loaded on the page yet. It seems like a classic page lifecycle issue where I can't call a function on an element that is not part of the document yet.

I know that the .click code or selector is correct because after the page loads, inside the console...I am able to emulate a click.

Any posts that can help me out with this? Essentially, I'm asking the page 'hey did you load all my controls yet? good, now click'.

<script type="text/javascript">
        $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
                sharePointReady();               
            });  
          $(".classnamehere").first().click();
        });
    </script>
Was it helpful?

Solution

You essentially want to use jQuery deferred methods and a promise to run something when the deferred is completed (or 'resolved').

Try this (you may need to modify sharePointReady() to return a a Deferred object instance):

<script type="text/javascript">
        $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
                sharePointReady().promise().done(function() {
                $(".classnamehere").first().click();
              });               
            });  

        });
    </script>

Full documentation is here:

http://api.jquery.com/deferred.promise/

http://api.jquery.com/promise/

There was a session at the SharePoint Conference in Las Vegas which went into detail about this method, and variations of it (all using Deferred and Promise), as the recommended way to handled chained (or just lots) of asynchronous events. Documentation (from what I see so far) is light at the moment, but I expect a lot more to come out over the coming months.

This post from Scott Hillier (who did the aforementioned session at SPC12), touches on this on his blog, complete with code samples from the demo he did - http://www.shillier.com/archive/2012/11/29/utilizing-promises-in-sharepoint-2013-apps.aspx

OTHER TIPS

Why not use the jQuery live method?

http://api.jquery.com/live/

It will pick up the controls when they become available.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top