in

Website animation with jQuery

jQuery is a library that makes common tasks for web developers a lot easier.

  • Manipulating the webpage
  • Responding to user events
  • Getting data from their servers
  • Building effects and animations

jQuery builds on top of the functionality that browser give us via the Javascript DOM API

Add jquery library to you html page

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>

If you are writing your jQuery on another page, make sure you add the jQuery source above your javascript file source

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
<script type=”text/javascript” src=”app.js”></script>

It’s all about the $

The $ keyword replaces document.querySelector()

document.querySelector(‘h1’)
document.querySelector(‘.classExample’)

Becomes

$(‘h1’)
$(‘.classExample’)

The only difference is that $ will select ALL of the H1. And not just the first one.

Manipulation

$(‘h1’).text(‘hello’)

This will change the text in ALL the h1 on the page

.text(‘hello’)

Is the same as in DOM API:

.textContent(‘hello)

You can add an id to target just one element

Use jQuery to modify existing text

var headingText = $(“#main-heading”).text();

This will return the text of element #main-heading in one long string and you can console.log(headingText)

$(“#main-heading”).text(“!!” + headingText + “!!”);

This will modify the existing headingText by adding !! before and after

To return the text &gt; text() ie zero arguments

$(“h1”).length;
How many h1(s) in the page ?

$(‘#heading’).html(‘hello <strong>john</strong’);
Use .html to modify the element with html</strong>

$(‘p’).css(‘color’, ‘red’)
Change the css of the element

$(‘h2’).addClass(‘newClass’)
Add a class

$(‘a’).attr(‘href’, ‘https://www.startupmag.co.uk’)
Modify all urls

$(‘img’).attr(‘src’, ‘https://www.urlofimage.com’)
Modify the picture with a new source

Creating elements with jQuery

Var newP = $(‘
’);
newP.text(‘hello paragraph’)
newP.addClass(‘className’)

Create an element that is a

(no need to close), add the text ‘hello paragraph’ and the class ‘className’

//append prepend after

$(‘body’).append(newP);

Add the new element at the end (append) of body

jQuery Collections vs. DOM Nodes

DOM functions return DOM Nodes
var headingFromD = document.getElementById(“myId”);
headingFromD.innerHTML = “Setting .innerHTML”;

Jquery returns jQuery collections
var headingFromJ = $(“#myId”); // jQuery collection
headingFromJ.html(“Using .html()”);

This just means that you can only apply respective methods to each. You canNOT for example use .html on DOM Nodes.

To keep things clear there is a naming convention.

var $headingFromJ > add a $ before.

Convert a jQuery collection into a DOM node

You have to treat the variable as an array with 1 element. And use index 0 to pull it out.

var $heading = $(“#cuteness”);
$heading.html(“Using jQuery again!”);
var headingD = $heading[0];

Convert a DOM node into a jQuery collection
var $headingJ = $(headingD);

Looping through jQuery collections

3 ways to do this:

//with for loop

var $paragraphs = $(‘p’);
for (var i = 0; i &lt; $paragraphs.length; i++) {
var element = $paragraphs[i]; // DOM node
var $paragraph = $(element);
$paragraph.html( $paragraph.html() + “..huzzah!”);
}

// each()

$paragraphs.each(function(index, element) {
var $paragraph = $(element);
$paragraph.html( $paragraph.html() + “..wowee!”);
});

// each with this

$paragraphs.each(function(index, element) {
var $paragraph = $(this);
$paragraph.html( $paragraph.html() + “..wowee!”);
});

Chaining jQuery methods

$(“<p>”)
.text(“new text”)
.addClass(“new”)
.appendTo(“body”);

Basically you can just add everything together with . Each part returns a collection. So you are just adding a method on the new returned collection.

Only difference with .appendTo(‘body’)

Instead of $(“body”).append(newP);

Adding event listeners with jQuery

<button id=”button-id”>Click Here</button>

$(“#button-id”).on(“click”, () =&gt; {
console.log(“I got clicked!!”);
});

Using event properties in jQuery

When user clicks anywhere on the page, show and image:

$(“body”).on(“click”, function(event) {
console.log(event);
var $img = $(“<img />”)
.attr(“src”, “https://www.kasandbox.org/programming-images/animals/crocodiles.png”)
.width(100)
.css(“position”, “absolute”)
.css(“top”, event.pageY + “px”)
.css(“left”, event.pageX + “px”)
.appendTo(“body”);
});

$(“#dog-pic”).on(“click”, function(event) {
var $dot = $(”
<div></div>
“);
$dot.addClass(“dot”);
$dot.appendTo(“body”);
$dot.css(“top”, event.pageY + “px”)
$dot.css(“left”, event.pageX + “px”)

});

DOM events and properties examples

Full list here

Mouse events

  • Mousedown
  • Mouseup

Keyboard events

  • Keydown,
  • Keypress
  • Keyup

Touch events (Mobile)

Drag Events
There is a draggable UI library:
https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js

Form Events

WindowEvents

Checking DOM readiness with jQuery

The DOM needs to be ready for jQuery or JS to work.

If jQuery is in a function jQueryCode(), by adding the following code, the page will only load jQuery when the DOM is ready. You can add this anywhere.

$(document).ready(function() {
jQueryCode();
});

Triggering events

Make the event launch even if the click hasn’t happened (good for testing):

$(“#abutton”).trigger(“click”);

DOM Animation and Effects with jQuery

Animation visibility with jQuery

Show / Hide

$(‘#pic’).hide();
$(‘#pic’).show();

Toggle()

$(‘#pic’).toggle();

Toggle will choose to show or hide the element depending on previous position.

Add speed/slowness to showing and hiding

$(‘#pic’).hide(1000);
$(‘#pic’).show(1000);

slideDown

$(‘#pic’).slideDown(1000);

Add delay

$(“#pic”).slideDown(2000, function() {
$(“#text”).fadeIn();
});

Only do the text fade in when the slideDown is finished.

Turn off ALL animations
$.fx.off

Animating numeric properties with jQuery

Animate object can animate any element that is numeric like width, opacity etc.

$(‘#pic).animate({
width: “400px”
marginLeft: “30px”
}, 1500);

$(‘#text’).animate({
fontSize: 40px
})

Using a descendant selector to select an element

<div class=”cat”><img src=”https://www.urlofimage.com” width=”150″ />$(‘.cat img’).animate({
width:’300px’
})

This will select the image in the class cat and animate the width.

What do you think?

Written by John

Leave a Reply

Your email address will not be published. Required fields are marked *

Use Regular Expressions with Javascript

Manipulating the DOM with Javascript