Keith

JQuery Animating HTML Elements

by Keith Rowles • 01/11/2023Framework

Landscape of desert and stars in sky at night

Summary

Using the JQuery JavaScript library to select and animate various html elements on a webpage and styling css.

The html content used in this example was taken from the book - Learning JQuery (Fourth Edition).

CDN

Place CDN link in webpage.

<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>

Add some styles which will be applied to the document.

html,
body {
  margin: 0;
  padding: 0;
}

body {
  font-family: Arial, Helvetica, sans-serif;
  color: black;
  background: white;
}

#container {
  font-size: 1.2em;
  margin: 10px 2em;
}

h1 {
  font-size: 2.5em;
  margin-bottom: 0;
}

h2 {
  font-size: 1.3em;
  margin-bottom: 0.5em;
}

h3 {
  font-size: 1.1em;
  margin-bottom: 0;
}

code {
  font-size: 1.2em;
}

a {
  color: blue;
}

#switcher {
  width: 300px;
  padding: 0.5em;
  border: 1px solid pink;
}

.label {
  width: 130px;
  margin: 0.5em 0;
  cursor: pointer;
  background-color: aliceblue;
}

.highlighted {
  background-color: yellow;
}
#container {
  display: none;
}

Here is the HTML.

<div id="container">
  <h2>Abraham Lincoln's Gettysburg Address</h2>
  <div id="switcher">
    <div class="label">Text Size</div>
    <button id="switcher-default">Default</button>
    <button id="switcher-large">Bigger</button>
    <button id="switcher-small">Smaller</button>
  </div>
  <div class="speech">
    <p>
      Fourscore and seven years ago our fathers brought forth on this continent
      a new nation, conceived in liberty, and dedicated to the proposition that
      all men are created equal.
    </p>
    <p>
      Now we are engaged in a great civil war, testing whether that nation, or
      any nation so conceived and so dedicated, can long endure. We are met on a
      great battlefield of that war. We have come to dedicate a portion of that
      field as a final resting-place for those who here gave their lives that
      the nation might live. It is altogether fitting and proper that we should
      do this. But, in a larger sense, we cannot dedicate, we cannot consecrate,
      we cannot hallow, this ground.
    </p>
    <a href="#" class="more">read more</a>
    <p>
      The brave men, living and dead, who struggled here have consecrated it,
      far above our poor power to add or detract. The world will little note,
      nor long remember, what we say here, but it can never forget what they did
      here. It is for us the living, rather, to be dedicated here to the
      unfinished work which they who fought here have thus far so nobly
      advanced.
    </p>
    <p>
      It is rather for us to be here dedicated to the great task remaining
      before us that from these honored dead we take increased devotion to that
      cause for which they gave the last full measure of devotion that we here
      highly resolve that these dead shall not have died in vain that this
      nation, under God, shall have a new birth of freedom and that government
      of the people, by the people, for the people, shall not perish from the
      earth.
    </p>
  </div>
</div>

Here is the js code.

$(document).ready(function () {
  var $speech = $('div.speech');

  var defaultSize = $speech.css('fontSize');

  $('#switcher button').click(function () {
    var num = parseFloat($speech.css('fontSize'));

    switch (this.id) {
      case 'switcher-large':
        num *= 1.4;

        break;

      case 'switcher-small':
        num /= 1.4;

        break;

      default:
        num = parseFloat(defaultSize);
    }

    $speech.animate({ fontSize: num + 'px' }, 'slow');
  });

  var $firstPara = $('p').eq(1);

  $firstPara.hide();

  $('a.more').click(function () {
    $firstPara.animate(
      {
        opacity: 'toggle',

        height: 'toggle',
      },
      'slow'
    );

    var $link = $(this);

    if ($link.text() == 'read more') {
      $link.text('read less');
    } else {
      $link.text('read more');
    }

    return false;
  });

  $('div.label').click(function () {
    var paraWidth = $('div.speech p').outerWidth();

    var $switcher = $(this).parent();

    var switcherWidth = $switcher.outerWidth();

    $switcher

      .css({ position: 'relative' })

      .fadeTo('fast', 0.5)

      .animate(
        {
          left: paraWidth - switcherWidth,
        },
        {
          duration: 'slow',

          queue: false,
        }
      )

      .fadeTo('slow', 1.0)

      .slideUp('slow', function () {
        $switcher.css({ backgroundColor: '#f00' });
      })

      .slideDown('slow');
  });

  $('p')
    .eq(2)

    .css('border', '1px solid #333')

    .click(function () {
      var $clickedItem = $(this);

      $clickedItem.next().slideDown('slow', function () {
        $clickedItem.slideUp('slow');
      });
    });

  $('p').eq(3).css('backgroundColor', '#ccc').hide();

  $('#container').fadeTo('slow', 1);

  $('p').hover(function () {
    $(this).toggleClass('highlighted');
  });

  $('h2').on('click', function () {
    var $h2 = $(this);

    $h2.animate(
      {
        opacity: '0.4',

        marginLeft: '20px',
      },
      'slow',
      'swing',
      function () {
        $('.speech').animate(
          {
            opacity: '0.5',
          },
          'slow'
        );
      }
    );
  });

  $('.speech').on('click', function () {
    var $speech = $(this);

    $speech.animate(
      {
        opacity: '1',
      },
      'slow'
    );
  });
});

Tech and Tools

  • CSS
  • HTML
  • jQuery
  • CodePen

Demo

Open demo on Code Pen.

Link to Demo