Search code examples
jquerycycle2

getJson and Cycle2


I am running a query to get a newsfeed in JSON format using getJson, which then I am placing within a div, as divs of their own to rotate using jQuery Cycle2. I can get jQuery Cycle2 to work with the news items when I hardcode them in the div, but when I add it through getJson, it does not fire. how can I change the dynamic content to load before the cycle is triggered?

I've even moved the javascript above the jQuery.Cycle2.js but have run out of ideas so I'm curious if anyone has had this happen before and how they deal with it.

My code so far


<div class="cycle-pager news-pager"></div>
<div id="news-area" class="cycle-slideshow oh"
data-cycle-swipe=true
data-cycle-swipe-fx=scrollHorz
    data-cycle-fx="scrollHorz"
    data-cycle-timeout="8000"
    data-cycle-auto-height="calc"
    data-cycle-pause-on-hover="true"
    data-cycle-pager=".news-pager"
    data-cycle-pager-event="mouseover"
    data-cycle-slides="> div"
>

</div>
<script> 
$.getJSON('https://mydomain.ca/feed/PressRelease.svc/GetPRList?apiKey=XXXX', function(data) {
               $.each(data.GetPRListResult, function(i, f) {
                  var tblRow = "<div class='news-item'><div class='heading date'>" + f.PressReleaseDate + "</div><h3><a href=https://investors.wfsinc.com" + f.LinkToDetailPage + ">" + f.Headline + "</a></h3></div>";
                    $(tblRow).appendTo("#news-area");


             });                    
           });
</script>

Solution

  • From Cycle2 main page:

    Auto-initialization is not supported for slideshows that are added to the DOM after jQuery's ready event has fired.

    And:

    You'd rather set your options via script than in the markup? Ok fine, have it your way.

    Since the .getJSON() method is async, you have no choice but to use the script way to instantiate Cycle.

    The Cycle2 documentation may be useful.

    It would be inside the .getJSON() callback.

    Notice I did not used the cycle-slideshow class which is used for the auto init...

    <div class="cycle-pager news-pager"></div>
      <div id="news-area" class="cycle-slideshow_notInitiated oh">
    </div>
    
    <script>
    $.getJSON('https://mydomain.ca/feed/PressRelease.svc/GetPRList?apiKey=XXXX', function(data) {
      $.each(data.GetPRListResult, function(i, f) {
        var tblRow = "<div class='news-item'><div class='heading date'>" + f.PressReleaseDate + "</div><h3><a href=https://investors.wfsinc.com" + f.LinkToDetailPage + ">" + f.Headline + "</a></h3></div>";
        $(tblRow).appendTo("#news-area");
      });
      
      // Instantiate Cycle here
      $(".cycle-slideshow_notInitiated ").cycle({
        swipe: true,
        "swipe-fx": "scrollHorz",
        fx: "scrollHorz",
        timeout: 8000,
        "auto-height": "calc",
        "pause-on-hover": true,
        pager: ".news-pager",
        "pager-event": "mouseover",
        slides: "> div"
      })
      
    });
    </script>