Move caption HTML creation to a separate function