|
/** |
|
* JS file for building an bootstrap image carousel from the images on a page |
|
*/ |
|
|
|
// Creating a custom expression for case insensitive alt attribute starts with |
|
// selector. Because the default e.g. $("img[alt^='Picture']") is case sensitive. |
|
$.expr[':'].altStartsWithCaseInsensitive = function(node, stackIndex, properties) { |
|
return node.alt.toLowerCase().indexOf(properties[3]) == 0; |
|
}; |
|
|
|
// This function checks if there are images in the post content whose "alt" |
|
// attribute starts with the given keyword (here the word "Picture"). If none |
|
// are found it does nothing more. If some are found they are moved to a built |
|
// Bootstrap carousel starting with the feature image of the post, which then |
|
// replaces the feature image at the top of the page. |
|
$(document).ready(function() { |
|
var keyword = "picture"; |
|
var carousel, postImages, featureImage, carousel, imagesParent, |
|
indicatorsParent, newDiv, newLi, carouselParent; |
|
|
|
// Get the additional images that should be displayed as a carousel. |
|
|
|
postImages = $('img:altStartsWithCaseInsensitive(' + keyword + ')'); |
|
// Build the carousel only if there are images for the carousel. |
|
if (postImages.length > 0) { |
|
// Start building the carousel. |
|
imagesParent = $('<div/>', { |
|
'class': 'carousel-inner', |
|
role: 'listbox' |
|
}); |
|
indicatorsParent = $('<ol/>', { |
|
'class': 'carousel-indicators' |
|
}); |
|
|
|
// Add feature image and its indicator to their respective parents. |
|
featureImage = $('.post-header img'); |
|
if (featureImage.length > 0) { |
|
newDiv = $('<div/>', { |
|
'class': 'item active' |
|
}); |
|
featureImage.appendTo(newDiv); |
|
newDiv.appendTo(imagesParent); |
|
newLi = $('<li/>', { |
|
'data-target': '#carousel-example', |
|
'data-slide-to': '0', |
|
'class': 'active' |
|
}); |
|
newLi.appendTo(indicatorsParent); |
|
} |
|
|
|
// Add additional images and corresponding indicators to their parents |
|
for (var i = 0; i < postImages.length; i++) { |
|
newDiv = $('<div/>', { |
|
'class': 'item' + ((i == 0 && featureImage.length == 0) ? ' active' : '') |
|
}); |
|
postImages.eq(i).appendTo(newDiv); |
|
newDiv.appendTo(imagesParent); |
|
|
|
//add li element to the ol of class "carousel-indicators" |
|
newLi = $('<li/>', { |
|
'data-target': '#carousel-example', |
|
'data-slide-to': (featureImage.length != 0 ? i + 1 : i), |
|
'class': (featureImage.length == 0 && i == 0 ? 'active' : '') |
|
}); |
|
newLi.appendTo(indicatorsParent); |
|
} |
|
|
|
// Finish building the carousel. |
|
carousel = $('<div/>', { |
|
id: 'carousel-example', |
|
'class': 'carousel slide', |
|
'data-ride': 'carousel' |
|
}); |
|
carousel.append(indicatorsParent, imagesParent); |
|
|
|
// Add the carousel to the DOM. |
|
carouselParent = $('.post-header'); |
|
$('.post-header img').remove(); |
|
carouselParent.prepend(carousel); |
|
} |
|
}); |