Custom JavaScript and CSS in Blogger posts

Right, here's a very simple tip (or trick?) that I half-expected wouldn't work, but it does. How does one add custom post-specific style (as in CSS) and logic (as in JavaScript) to Blogger posts? This could be useful for inserting examples right into your articles.
You just do it (and I am not even affiliated with Nike!)

First thing to do it switch to the HTML composing mode:



You will see your article (if already typed) in all its gory glory — HTML code and all!

Here you can insert your custom HTML element, in my case I add a DIV that will serve as a custom button:
<div id="custom-button">Button</div>

In order to add custom style to it, insert your CSS code between the <style> tags, as you do:
<style>
#custom-button {
    color: white; 
    font-weight: bold; 
    background-color: #06a; 
    margin: 2em auto; 
    text-align: center; 
    line-height: 70px; 
    height: 70px; 
    width: 70px; 
    -webkit-border-radius: 100%; 
    -moz-border-radius: 100%; 
    border-radius: 100%;
}
</style>

Then, if you need to include an external library, which in my case happens to be jQuery, you can add it by inserting:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript">
</script>

You'll notice I've linked it from Google's CDN (Content Delivery Network), it is more than adequate for smaller sites (such as your humble servant's).

And, to finally add your custom JavaScript logic, insert the code between <script> tags:
<script>
$('#custom-button').click(function() {
    alert('It works!');
});
</script>

Post a Comment