-1

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
nclsvh
  • 2,628
  • 5
  • 30
  • 52

2 Answers2

1

You should add your click event to body like

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

Because you add elements dynamically!

Michael
  • 321
  • 2
  • 13
  • Thanks Michael, this worked indeed!! There is just a small typo in your code above, see the dot before the function needs to be a comma. – nclsvh Jun 12 '15 at 14:28
  • !! Just uploaded it and tested this on chrome/firefox/safari and all the mobile versions of that. Works perfectly except on Safari iOS, nothing happening there.. – nclsvh Jun 12 '15 at 14:47
0

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");
    });
}
Scheda
  • 526
  • 5
  • 11