Monday, 28 April 2014

jQuery second word plugin

You've seen those fancy titles where the second word is a different colour from the first. To achieve this, you really don't want to have to put span tags all around your code. Below I've created a plugin which allows you to decide which elements have their second word looking different from the first. You can use it with any framework. Please excuse the separate CSS file, but I've been using LiveStyle with Sublime Text 2. It really speeds development up.
First the HTML:
<!DOCTYPE html>
<html lang="en">
  <head>  
    <title>Second word</title>  
    <link href='style.css' rel='stylesheet' type='text/css'>  
  </head>
  <body>
    <header>
      <h1>Second word</h1>
    </header>
    <section>
      <article>
        <h2>Sub header</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sin tantum modo ad indicia veteris memoriae cognoscenda, curiosorum. Si verbum sequimur, primum longius verbum praepositum quam bonum. Duo Reges: constructio interrete. Falli igitur possumus. Egone non intellego, quid sit don Graece, Latine voluptas? Sed virtutem ipsam inchoavit, nihil amplius. Sed eum qui audiebant, quoad poterant, defendebant sententiam suam.</p>
      </article>
      <article>
        <h2>Sub heading</h2>
        <p>Quis est, qui non oderit libidinosam, protervam adolescentiam? Nam si amitti vita beata potest, beata esse non potest. Recte, inquit, intellegis. Idemne potest esse dies saepius, qui semel fuit? Venit enim mihi Platonis in mentem, quem accepimus primum hic disputare solitum; Aliter enim explicari, quod quaeritur, non potest. Profectus in exilium Tubulus statim nec respondere ausus; Nos vero, inquit ille;</p>
      </article>        
    </section>
    <footer><p>&copy; Second word 2014</p></footer>  
    <script src="https://code.jquery.com/jquery.js"></script>
    <script src="secondword.plugin.js"></script>
    <script>
    (function()
    {
        $('header > h1, article > h2').secondword();
    })();
    </script>
  </body>
</html>

Now the style.css:
body
{
padding:1em;
font-family:Sans-serif;
}
header, footer, article > h2
{
font-family:Serif;
color:red;
font-style:italic;
}
section > article
{
text-align:justify;
line-height:1.7;
}
body, header > h1 span.secondword, article > h2 span.secondword
{
color:#777;
}

And finally, the jQuery plugin, secondword.plugin.js:
(function($)
{
  $.fn.secondword = function()
  {
    $(this).each(function()
    {
      var text = $(this).text().split(' ');
      if(text.length < 2) return;
      text[1] = '<span class="secondword">'+text[1]+'</span>';
      $(this).html(text.join(' '));
    });
  }
})(jQuery);

No comments:

Post a Comment