4.3 Toggle Visibility of Solutions
When the bookdown file loads, you would like all the solutions to be hidden. You would like a button for each solution to toggle its visibility.
Easy solution: this works but cannot show math equations properly. ❌
- Advantage is that it does not need to define any java function.
<button class="button" onclick="$('#target2').toggle();">
Show/Hide
</button>
<div id="target2" style="display: none">
Solution:
$P(\textrm{A wins or B wins}) = P\big(\{\textrm{A wins}\} \cup \{\textrm{B wins}\}\big)$
</div>
Example:
Ultimate solution!
Able to show math equations properly ✅
Put the following codes in the Rmd header. This defines the button action
myFunction
.<script> function myFunction(id) { var x = document.getElementById(id); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script>
In case of
bookdown
, put the JavaScript inscript.hhml
, which will be loaded into the header of all your html files via_output.yml
.When you want to create a solution division, use the following codes.
- Change the function argument
myDIV
, which is theid
of the element.id
must be unique in one file. - Change the text shown on the button (
Solution1
) if you need. - Put your solution inside the
<div id=myDIV>
tag, whereid
is what you specified in the function argument.
- Change the function argument
```{example, ex1}
Let $Y=g(X)=\mu+\sigma X$ where $\sigma>0$. Representing the CDF of $Y$ using $F_X(x)$.
```
<button onclick="myFunction('myDIV')">Solution1</button>
<div id="myDIV" style="display: none; color: blue;">
$P(\textrm{A wins or B wins}) = P\big(\{\textrm{A wins}\} \cup \{\textrm{B wins}\}\big)$
solution1
</div>
```{example, ex2}
Let $X\sim N(0,1)$ and $Y=\mu+\sigma X$. Calculate $\mathbb{E}(Y)$.
```
<button onclick="myFunction('myDIV2')">Solution2</button>
<div id="myDIV2" style="display: none; color: blue;">
$P(\textrm{A wins or B wins}) = P\big(\{\textrm{A wins}\} \cup \{\textrm{B wins}\}\big)$
solution2
</div>
blabla ...
blabla ...
Example 4.1 Let \(Y=g(X)=\mu+\sigma X\) where \(\sigma>0\). Representing the CDF of \(Y\) using \(F_X(x)\).
References: