jQuery Integration

This guide shows how to fetch and display Instagram posts using jQuery and the Feedframer REST API.

Installation

Include jQuery in your HTML:

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

Basic Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instagram Feed</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        .instagram-feed {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            padding: 20px;
        }
        .post {
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
        }
        .post img {
            width: 100%;
            height: 300px;
            object-fit: cover;
        }
        .post-caption {
            padding: 15px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div id="instagram-feed" class="instagram-feed"></div>

    <script>
        $(document).ready(function() {
            const apiKey = 'YOUR_API_KEY'; // Replace with your API key
            const apiUrl = `https://feedframer.com/api/v1/me?api_key=${apiKey}&page[size]=12`;

            $.ajax({
                url: apiUrl,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    const posts = response.posts;

                    posts.forEach(function(post) {
                        const postHtml = `
                            <div class="post">
                                <img src="${post.mediaUrl}" alt="${post.caption || 'Instagram post'}">
                                <div class="post-caption">
                                    <p>${post.caption || ''}</p>
                                </div>
                            </div>
                        `;

                        $('#instagram-feed').append(postHtml);
                    });
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching posts:', error);
                    $('#instagram-feed').html('<p>Error loading Instagram posts.</p>');
                }
            });
        });
    </script>
</body>
</html>

With Filtering

$(document).ready(function() {
    const apiKey = 'YOUR_API_KEY';

    // Fetch only images
    const apiUrl = `https://feedframer.com/api/v1/me?api_key=${apiKey}&filter[type]=IMAGE&page[size]=9`;

    $.ajax({
        url: apiUrl,
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            renderPosts(response.data);
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
        }
    });
});

function renderPosts(posts) {
    posts.forEach(function(post) {
        const { caption, mediaUrl, permalink } = post;

        const postHtml = `
            <div class="post">
                <a href="${permalink}" target="_blank">
                    <img src="${mediaUrl}" alt="${caption || 'Instagram post'}">
                </a>
                <div class="post-info">
                    <p>${caption || ''}</p>
                    <span>❤️ ${likeCount}</span>
                </div>
            </div>
        `;

        $('#instagram-feed').append(postHtml);
    });
}

With Pagination

let currentCursor = null;

function loadPosts(cursor = null) {
    const apiKey = 'YOUR_API_KEY';
    let apiUrl = `https://feedframer.com/api/v1/me?api_key=${apiKey}&page[size]=12`;

    if (cursor) {
        apiUrl += `&page[cursor]=${cursor}`;
    }

    $.ajax({
        url: apiUrl,
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            renderPosts(response.data);

            // Show/hide load more button
            if (response.links.next) {
                // Extract cursor from next link
                const nextUrl = new URL(response.links.next);
                currentCursor = nextUrl.searchParams.get('page[cursor]');
                $('#load-more').show();
            } else {
                $('#load-more').hide();
            }
        },
        error: function(xhr, status, error) {
            console.error('Error:', error);
        }
    });
}

$(document).ready(function() {
    loadPosts();

    $('#load-more').click(function() {
        loadPosts(currentCursor);
    });
});
<div id="instagram-feed"></div>
<button id="load-more" style="display: none;">Load More</button>

Error Handling

$.ajax({
    url: apiUrl,
    method: 'GET',
    dataType: 'json',
    success: function(response) {
        if (response.data && response.data.length > 0) {
            renderPosts(response.data);
        } else {
            $('#instagram-feed').html('<p>No posts found.</p>');
        }
    },
    error: function(xhr, status, error) {
        let errorMessage = 'Error loading Instagram posts.';

        if (xhr.status === 401) {
            errorMessage = 'Invalid API key. Please check your credentials.';
        } else if (xhr.status === 429) {
            errorMessage = 'Rate limit exceeded. Please try again later.';
        }

        $('#instagram-feed').html(`<p>${errorMessage}</p>`);
        console.error('API Error:', xhr.responseJSON);
    }
});

Lightbox Integration

Here's an example integrating with a simple lightbox:

function renderPosts(posts) {
    posts.forEach(function(post) {
        const { caption, mediaUrl, permalink } = post;

        const postHtml = `
            <div class="post">
                <img src="${mediaUrl}"
                     alt="${caption || 'Instagram post'}"
                     data-permalink="${permalink}"
                     class="lightbox-trigger">
                <p>${caption || ''}</p>
            </div>
        `;

        $('#instagram-feed').append(postHtml);
    });

    // Bind lightbox click events
    $('.lightbox-trigger').click(function() {
        const imageUrl = $(this).attr('src');
        const permalink = $(this).data('permalink');

        // Open your lightbox here
        openLightbox(imageUrl, permalink);
    });
}

function openLightbox(imageUrl, permalink) {
    // Your lightbox implementation
    const lightboxHtml = `
        <div id="lightbox" class="lightbox">
            <span class="close">&times;</span>
            <img src="${imageUrl}" alt="Instagram post">
            <a href="${permalink}" target="_blank">View on Instagram</a>
        </div>
    `;

    $('body').append(lightboxHtml);

    $('.close').click(function() {
        $('#lightbox').remove();
    });
}

AJAX Settings

For better performance and control:

$.ajaxSetup({
    timeout: 10000, // 10 second timeout
    cache: true     // Enable caching for better performance
});

// Fetch posts
$.ajax({
    url: apiUrl,
    method: 'GET',
    dataType: 'json',
    beforeSend: function() {
        $('#instagram-feed').html('<p>Loading...</p>');
    },
    success: function(response) {
        $('#instagram-feed').empty();
        renderPosts(response.data);
    },
    error: function(xhr, status, error) {
        handleError(xhr, status, error);
    },
    complete: function() {
        console.log('Request complete');
    }
});

Best Practices

  1. Cache API responses - Use jQuery's cache option or implement your own caching
  2. Handle errors gracefully - Always provide user feedback for failures
  3. Lazy load images - For better performance with many posts
  4. Debounce - If implementing search/filter features
  5. Escape HTML - Sanitize caption text before displaying
function escapeHtml(text) {
    return $('<div>').text(text).html();
}

// Use it when rendering
const safeCaption = escapeHtml(post.caption);

Next Steps