Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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>
share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted

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

share|improve this answer
    
funny, I studied that but didn't think of applying it here. –  bitterac Nov 30 '12 at 22:35
add comment

Why not use the jQuery live method?

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

It will pick up the controls when they become available.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.