Is there a way to show/hide code interactively in a R Markdown/Knitr report?
If I understood you correctly, you could do that at least by using the HTML output, like in this minimal example:
---
title: "Toggle Code boxes"
output: html_document
date: "January 12, 2016"
---
First add the javascript to toggle boxes(remember to indent it)
<script language="javascript">
function toggle(num) {
var ele = document.getElementById("toggleText" + num);
var text = document.getElementById("displayText" + num);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
and then we have some R code with the toggle button wrapped around (also indented):
<a id="displayText" href="javascript:toggle(1);">Show underlying code</a>
<div id="toggleText1" style="display: none">
```{r}
x <- sample(100)
mean.x <- mean(x)
```
</div>
The mean is `r mean.x`. Please click the link to see the source code.
<a id="displayText" href="javascript:toggle(2);">Show underlying code</a>
<div id="toggleText2" style="display: none">
```{r}
median.x <- median(x)
```
</div>
And the median is `r median.x`. Please click the link to see the source code.
Related
I am trying to generate a button from a range X; in this case, from 0 to 25, and when I click in one generate button, it will alert the word eggs. I followed the rules to generate an on click event on an element through JavaScript, but the code didn't work. What is wrong with the code?
The code is in the link. Unfortunately, I couldn't upload it through CTRL+K stackoverflow feature.
https://textuploader.com/1gynb
Hei,
Not a javascript expert but I think this does what you want:
<p id='ai'>Click the button to make a BUTTON element with text.</p>
<button onclick="generator()">Try it</button>
<script>
function generator() {
for (var x = 0; x < 26; x++) {
var btn = document.createElement("BUTTON");
btn.innerHTML = x;
btn.setAttribute("onclick", "myFunction();");
document.getElementById('ai').innerHTML += btn.outerHTML;
}
}
function myFunction() {
console.log("done")
}
</script>
I want to add image and text to popup of leaflet map such as this link:
https://www.bookdepository.com/
I can add image But How I can add text near the image?
my code is here:
<div id="map" style="width:270px;height:310px;"></div>
<?php
$matrix = [
[34.05777800, 51.48416700],
[38.50972200, 46.65444400],
[29.26666700, 51.21666700],
[34.05777800, 51.48416700],]
?>
<script type="text/javascript">
var matrix = JSON.parse('<?php echo json_encode($matrix);?>');
var map = L.map('map').setView(matrix[0],7);
var i = 1;
function myLoop() {
setTimeout(function () {
var div = L.DomUtil.create('div', 'my-div');
var img = L.DomUtil.create('img', 'my-img',div);
img.style.width = '60px';
img.style.height = '80px';
div.style.textAlign = 'right';
img.src = 'http://127.0.0.1:8000/productImages/64517.jpg';
L.marker(matrix[i]).addTo(map)
.bindPopup(div)
.openPopup();
map.flyTo(matrix[i]);
i++;
if (i < 10) {
myLoop();
}
}, 6000)
}
L.tileLayer('https://stamen-tiles
{s}.a.ssl.fastly.net/watercolor/{z}/{x}/{y}.{ext}', {
ext: 'jpg'
}).addTo(map);
myLoop();
</script>
My output is this pic:
You can use bindpopup function of leaflet to attach a pop up with your custom html.
marker.bindPopup("<div>Your custom html</div>");
You can find more information here.
You can indeed use the .bindPopup method like this (in your case) :
matrix
.bindPopup("<div> <p>Text</p> <img src="path/or/url"/> </div>");
Nevertheless it seems that using the css background-image in a <span> tag as popup image doesn't work correctly, I recommend using an <img> tag.
Hope it's helpful, you can find more information on methods there.
I want to indent TOC according to header level.
My example document looks like this:
# Tutorial
## Start a new project
### Project structure
### Analysis code
I'm compiling Rmd document with:
rmarkdown::render("foo.Rmd",
output_options = HTMLlook,
output_file = "foo.html")
HTMLlook <- list(toc = TRUE,
toc_depth = 5,
toc_float = list(collapsed = FALSE,
smooth_scroll = TRUE))
This produces document with TOC
However, I want indented TOC (indentation equivalent to header level). Wanted result should look like this:
Is it possible to set this option in render or maybe pass css parameters to it?
I am not aware of a built-in solution. But here is a little tweak:
<script>
$(document).ready(function() {
$items = $('div#TOC li');
$items.each(function(idx) {
num_ul = $(this).parentsUntil('#TOC').length;
$(this).css({'text-indent': num_ul * 10, 'padding-left': 0});
});
});
</script>
The depth of your headers is actually mapped inside the TOC. For each level you go down, a new ul element is created. This is what we are making use of here. In detail:
When the document has finished loading ($(document).ready(....):
Select all list items inside the element with id TOC
For each list item count the number of parent elements until you reach the element with id TOC. This is the number of ul elements.
Change the style for the current list item according to the number of parents.
You can tweak the spacing by playing around with the two parameters for text-indent and padding-left.
MRE:
---
title: "Habits"
author: Martin Schmelzer
date: September 14, 2017
output:
html_document:
toc: true
toc_depth: 5
toc_float:
collapsed: false
smooth_scroll: true
---
<script>
$(document).ready(function() {
$items = $('div#TOC li');
$items.each(function(idx) {
num_ul = $(this).parentsUntil('#TOC').length;
$(this).css({'text-indent': num_ul * 10, 'padding-left': 0});
});
});
</script>
# In the morning
## Waking up
### Getting up
#### Take a shower
##### Make coffee
# In the evening
## Make dinner
This is the result:
I am using bookdown (html) instead of slides in lectures. I really would like to create blocks that appear/disappear to include questions` solutions.
Probably I can do it by css. But I do not now how to do this and also include my css without mess with the bookdown css
Example:
Question: bla bla bla ?
Solution uncover
When I click in uncover I could show my R code and output.
That would be great :)
You can achieve what you want through the knitr hooks. When you set a hook option for code chunk (in this example uncover = TRUE), it will trigger the corresponding hook function uncover, and the hook can write something before and after the html code generated from the chunk output.
In the code below, I first define a Javascript function function uncover(id) which can uncover certain html element by id. And I let the hook uncover to generate a html button which calls the Javascript function before the chunk output and wrap the output with a div with certain id and style.display =none`. You can make modification to the code below to adapt to your need, but the idea is like this.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
uncover <- function(before, options, envir) {
if (before) {
id <- options$id
button_string <- paste0("<button onclick=\"uncover('",
id,
"')\">Uncover</button>")
div_string <- paste0("<div id = '", id,
"', style = 'display:none'>")
paste0(button_string, "\n", div_string)
}
else {
"</div>"
}
}
knitr::knit_hooks$set(uncover = uncover)
```
<script>
function uncover(id) {
var x = document.getElementById(id);
x.style.display = 'block';
}
</script>
```{r, uncover = TRUE, id = "script"}
1 + 1
```
Edit at 05/03/2020
Currently, knitr or pandoc or something else in the toolchain refuses to convert invisible markdown elements into valid HTML, so the solution above does not work perfectly. One solution is to make all the things visible at first, but provide a button to hide them like the following:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
uncover <- function(before, options, envir) {
if (before) {
id <- options$id
button_string <- paste0("<button onclick=\"uncover('",
id,
"')\">Uncover</button>")
div_string <- paste0("<div id = '", id,
"' class = 'cover'>")
paste0(button_string, "\n", div_string)
}
else {
"</div>"
}
}
knitr::knit_hooks$set(uncover = uncover)
```
```{r, uncover = TRUE, id = "script"}
1 + 1
```
<script>
function uncover(id) {
var x = document.getElementById(id);
x.style.display = 'block';
}
function cover() {
var xs = document.getElementsByClassName('cover');
for(count = 0; count < xs.length; count++) {
xs[count].style.display = 'none';
}
}
</script>
<button onclick="cover()">Cover all</button>
I wish to knit an html file from an R Notebook that contains paged tables with hyperlinks.
Hyperlinks can be inserted using knitr::kable, but I can't find a way to generate a paged table with this function.
Paged tables are the default notebook output, but I can't find a way of inserting functional hyperlinks. Many thanks for your help.
---
title: "Paged notebook table with hyperlinks"
output:
html_notebook:
code_folding: "hide"
---
```{r rows.print=3}
wiki.url <- "https://en.wikipedia.org/wiki/"
df1 <- data.frame(Month=month.name, URL=paste0("[", month.name, "](", wiki.url, month.name, ")"))
df2 <- data.frame(Month=month.name, URL=paste0("<a href='", wiki.url, month.name, "'>", month.name, "</a>"))
print(df1)
```
```{r rows.print=3}
print(df2)
```
```{r rows.print=3}
knitr::kable(df1)
```
```{r rows.print=3}
knitr::kable(df2)
```
Since there doesn't seem to be a perfect solution to my problem, I thought I'd post the workaround that I came up with - in case someone has a similar problem.
I created the table plus hyperlinks with knitr::kable and then added an html button and inline javascript to toggle visibility - not as elegant as a paged table, but does the job.
Note the <script> tag at the bottom of the file that hides tables by default.
(Paste code into an .Rmd file in RStudio):
---
title: "Managing large tables with hyperlinks in html notebook"
output:
html_notebook:
code_folding: "hide"
---
<script>
function myFunction(id) {
var x = document.getElementById(id);
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
```{r}
library(knitr)
df1 <- data.frame(Month=month.name, Link=paste0("[", month.name, "](https://en.wikipedia.org/wiki/", month.name, ")"))
```
<button class="button" onclick="myFunction('DIV_months')">Show/hide table</button>
<div id="DIV_months" class="div_default_hide">
```{r}
knitr::kable(df1)
```
</div>
<script>
var divsToHide = document.getElementsByClassName("div_default_hide");
for(var i = 0; i < divsToHide.length; i++)
{
divsToHide[i].style.display = 'none';
}
</script>