getJSON loading to slow, .toggle() not triggering

575 views Asked by At

Purpose = toggle a section 'more info' for a specific item in a list
Problem = a simple jQuery .toggle() isn't working
Possible cause = getJSON loads to slow

I am loading a foursquare json to get venues around my current location. I then .append() those venues with jQuery to my HTML. After that I have a function to toggle a section with 'more info' on a click-event.

After some searching I think I found the problem. My getJSON starts loading and then my next function is loaded in jQuery. After this next function is loaded (which is my .toggle()) the getJSON finally finishes. So I think my function with my .toggle() can't find the classes to toggle, because they are not yet in my HTML because my getJSON isn't finished loading the data.

Here is my jQuery code.
And the output of my console in my browser has this order:

loaded 4sq venues                    line 29
toggle function loaded               line 33
200                                  line 10

It's because of this meta.code on line 10 that I believe the getJSON is to slow loading...

I hope I made myself clear enough.
Thanks in advance

2

There are 2 answers

2
Michael On BEST ANSWER

You should add your click event to body like

$('body').on('click', '.venueLabel', function(){
     $(".venueMore").toggle("slow");
});

Because you add elements dynamically!

0
Scheda On

getJSON is going to be asynchronous. Which means it won't stop other Javascript from running while it's doing it's thing.

You should use a callback in getFoursquareVenues. Example below.

$(window).load(function() {
    getFoursquareVenues(openDetailVenues());
});

function getFoursquareVenues(callback) {

    $.getJSON("https://api.foursquare.com/v2/venues/search?client_id=placeholder&client_secret=placeholder&v=20130815&ll=51.0824401,3.714485&query=cafe", function(data) {

        console.log(data.meta.code);

        $('#venueList').html();
        var content = '';

        $.each(data.response.venues, function(index, elm) {
            content += '' + '<div class="venue col-xs-12">' + '<div class="venueLabel" id="' + elm.id + '">' + elm.name + '</div>' + '<div class="venueMore">' + elm.location.address + elm.hereNow.count + '</div>' + '</div>'
        });
        $('#venueList').append(content);

        if (callback) { callback() };
    });
    console.log('loaded 4sq venues');
}

function openDetailVenues() {
    console.log('toggle function loaded');
    $(".venueLabel").click(function() {
        $(".venueMore").toggle("slow");
    });
}