Use js to toggle code in Hexo

Add a button for toggle

It is easy to figure out that hexo will rendered the code to highlight class.

1
2
1 the code will be rendered with class code
2 while the number will be rendered with class gutter

So, we can just add a button to control all the highlight class.
Of cause, you can control the code class or gutter class or whatever.

1
<button onclick="$('.highlight').toggle();">Toggle</button>

write the toggle function

use hexo’s tag plugins to insert the javascript code.

If certain content is causing processing issues in your posts, wrap it with the raw tag to avoid rendering errors.

1
2
3
{% raw %}
content
{% endraw %}

Here is the code referenced from stackoverflow stackoverflow

1
2
3
4
5
6
7
8
9
10
11
12
13
{% raw %}
<script>
code_show=true;
function toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
</script>
{% endraw %}

Even though the Jquery select a not exist ‘div.input’, but the code still work, amazing!
Because you already select the ‘.highlight’ before calling toggle() function.
In other word, as long as the Jquery hide and show function are there, what element is chose does not matter.

A more general Version

1
2
3
4
5
6
7
8
9
10
11
12
13
{% raw %}
<script>
code_show=true;
function Toggle(what) {
if (code_show){
$(what).hide();
} else {
$(what).show();
}
code_show = !code_show
}
</script>
{% endraw %}

What is more

Any raw js, css or some certain content can be used with hexo’s tag plugins.

That means we can use Hexo to write markdown that can be rendered into any html that we want.

In this case, since we have to use Jquery, we can just use Raw tag plugins or install hexo-jquery.

  1. 1
    2
    3
    {% raw %}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    {% endraw %}
  2. npm install –save hexo-jquery

Reference

https://hexo.io/docs/tag-plugins.html
https://stackoverflow.com/questions/27934885/how-to-hide-code-from-cells-in-ipython-notebook-visualized-with-nbviewer
https://www.npmjs.com/package/hexo-jquery