Skip to content

Restricting Instafeed.js Caption Length

Issue Description

This isn’t really an issue, as such, more of a handy bit of functionality.

If you’re needing to restrict the length of a caption from Instafeed.js you can use this little filter snippet.

Affected Browsers

  • all

Issue Type

Fixed Code Snippets

// Restrict the caption to 40 characters
filter: function(image) {
	var MAX_LENGTH = 40;
	// here we create a property called "short_caption"
	// on the image object, using the original caption
	if (image.caption && image.caption.text) {
		image.short_caption = image.caption.text.slice(0, MAX_LENGTH);
	} else {
		image.short_caption = "";
	}
	// ensure the filter doesn't reject any images
	return true;
},
// Restrict the caption without chopping a word in half
filter: function(image) {
	var MAX_LENGTH = 140;
	var closestIndex = MAX_LENGTH;

	if (image.caption && image.caption.text) {
		while(true) {
			if (image.caption.text.charAt(closestIndex) === ' ') {
				break;
			}
			closestIndex -= 1;
		}
		image.short_caption = image.caption.text.slice(0, closestIndex);
	} else {
		image.short_caption = '';
	}

	return true;
},

References

Reference Description

Reference Link

Stackoverflow solution

Back to Issues List