Search code examples
jqueryrflexdashboard

Insert a link in each image of carousel in R with jQuery


I tried add a link in each image of a carousel in R. My code (the images is not reproducible. You must use an image from your computer):

---
title: "Statistics"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
    theme: spacelab
---

```{r}
library(flexdashboard)
library(shiny)
library(broom)
library(scales)
library(kableExtra)
library(bsplus)
library(htmltools)
```

aaaaaaaaaaaaaaaaaaaaaaa
===========================================

Column {}
-------------------------------------------

```{r}
bs_carousel(id = "the_beatles", use_indicators = 
TRUE) %>%
  bs_append(
content = bs_carousel_image(src = "img/image_2.jpg"),
caption = bs_carousel_caption("John Lennon", "Rhythm guitar, vocals")
  ) %>%
  bs_append(
content = bs_carousel_image(src = "img/image_1.jpg"),
caption = bs_carousel_caption("Paul McCartney", "Bass guitar, vocals")
  )
```
  • How insert a clickable link in each image of carousel (image_1 and image_2)?

For example, by clicking in carousel image_1 the user is directed to the website www.stackoverflow.com; and if clicking in carousel image_2 the user is directer to website www.google.com.

To place the same link on all images, I put this code (jQuery) below the YAML header:

<script>
$('.carousel-inner>.item>img').wrap('<a href = "https://www.stackoverflow.com" 
target = "_blank">');
</script>

But, I want a link for each image.

Thanks.


Solution

  • You can use this script:

    <script>
    var urls = ["https://www.stackoverflow.com", "https://www.google.com"]
    $('.carousel-inner>.item>img').wrap(function(i){
    return '<a href = "' + urls[i] + '" target = "_blank">'
    });
    </script>