Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Dynamic Content and Visual Effects with jQuery 2: AJAX, JSON, and Interactive UI

Tech 1

Working with Dynamic Content via AJAX and JSON

AJAX-powered content updates let you modify parts of a page without a full refresh, turning static websites into interactive web applications. Below are practical recipes for common AJAX and JSON use cases with jQuery.

Load Server-Generated HTML into a Page Element

At its most basic, AJAX lets you update a single DOM element with new content from a server. This example walks through creating a random quote widget with PHP and jQuery.

Steps

  1. Create a PHP file get-quote.php in your web root with the following code to serve a random quote:
<?php
$random_num = rand(1, 5);
$random_quote = "";
switch ($random_num) {
  case 1:
    $random_quote = "Learn from yesterday, live for today, hope for tomorrow. The important thing is not to stop questioning.";
    break;
  case 2:
    $random_quote = "Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.";
    break;
  case 3:
    $random_quote = "The difference between stupidity and genius is that genius has its limits.";
    break;
  case 4:
    $random_quote = "Try not to become a man of success, but rather try to become a man of value.";
    break;
  case 5:
    $random_quote = "Any man who can drive safely while kissing a pretty girl is simply not giving the kiss the attention it deserves.";
    break;
}
echo $random_quote;
?>
  1. Create an HTML file quote-widget.html with the following markup:
<html>
<head>
  <title>Random Quote Widget</title>
  <script src="jquery.min.js"></script>
  <style type="text/css">
  .sidebar {
    width: 200px;
    background-color: #CCC;
    float: left;
    height: 140px;
    text-align: center;
    font-size: 25px;
    padding: 10px;
    padding-top: 40px;
  }
  .content-area {
    width: 300px;
    float: left;
    margin-left: 10px;
    background-color: #333;
    color: #FFF;
    height: 140px;
    font-size: 20px;
    position: relative;
    padding: 20px 10px 10px 10px;
  }
  .new-quote-btn {
    position: absolute;
    right: 5px;
    top: 5px;
  }
  </style>
  <script>
  $(function() {
    $('.new-quote-btn').click(function() {
      $.ajax({
        url: '/get-quote.php',
        method: 'GET'
      }).done(function(response){
        $('.current-quote').html(response);
      });
    });
  });
  </script>
</head>
<body>
  <div class="sidebar">
    Famous <br />Einstein Quotes
  </div>
  <div class="content-area">
    <p class="current-quote"></p>
    <button class="new-quote-btn">Get Quote</button>
  </div>
</body>
</html>

How it works

The PHP script generates a random number between 1 and 5, selects a matching quote, and outputs it as plain text. The HTML creates a two-column layout, with a trigger button and an empty paragraph to hold the quote. The jQuery code attaches a click handler to the button that sends a GET AJAX request to the PHP script. When the request succeeds, the response text is inserted into the quote paragraph, updating the content without a page refresh.


Handle AJAX Server Errors

Network and server issues are unavoidable in web development, so you need to provide clear feedback to users when something goes wrong. jQuery provides both global and per-request error handling.

Steps

  1. Create ajax-error-demo.html with the following markup:
<html>
<head>
  <title>AJAX Error Handling Demo</title>
  <script src="jquery.min.js"></script>
  <script>
  $(function() {
    $('#trigger-request').click(function() {
      $.ajax({  
        url: 'missing-file.html',
        method: 'GET'
      }).done(function(data){
        // Will never run for a missing file
      });
    });

    // Global error handler for all AJAX requests
    $(document).ajaxError(function(event, xhr, settings) {
      alert(`Request failed for ${settings.url}. Status: ${xhr.status} ${xhr.statusText}`);
    });
  });
  </script>
</head>
<body>
  <button id="trigger-request">Send AJAX Request</button>
</body>
</html>

How it works

This example tries to request a file that does not exist, triggering an error. The global ajaxError handler attached to the document catches all failed AJAX requests on the page and displays error details to the user.

For per-request error handling (different behavior for different requests), you can use the fail() callback directly on the AJAX call:

$.ajax({
  url: 'missing-file.html',
  method: 'GET'
}).done(function(data){
  // Success logic here
}).fail(function(xhr){
  alert(`Request failed. Error code: ${xhr.status}`);
});

Process JSON Data

JavaScript Object Notation (JSON) is a lightweight, widely supported data format ideal for transferring data between server and client.

Steps

  1. Create get-people.php to output JSON formatted data:
<?php
// Create an array of character data
$characters = [
  1 => [
    "firstname" => "Luke",
    "lastname" => "Skywalker"
  ],
  2 => [
    "firstname" => "Darth",
    "lastname" => "Vader"
  ],
  3 => [
    "firstname" => "Mace",
    "lastname" => "Windu"
  ]
];
// Set correct content type for JSON
header("Content-Type: application/json; charset=UTF-8");
// Encode array to JSON and output
echo json_encode($characters);
?>
  1. Create json-demo.html to process and display the JSON data:
<html>
<head>
  <title>JSON Processing Demo</title>
  <script src="jquery.min.js"></script>
  <script>
  $(function(){
    $.ajax({
      url: '/get-people.php',
      method: 'GET'
    }).done(function(data){
      $.each(data, function(id, character) {
        $('#character-list').append("<li>#${id} ${character.firstname} ${character.lastname}</li>");
      });
    });
  });
  </script>
</head>
<body>
  <ul id="character-list"></ul>
</body>
</html>

How it works

The PHP script defines an array of character data, sets the correct response headers so jQuery recognizes the response as JSON, encodes the array to JSON format, and outputs it. On the client side, jQuery automatically parses the JSON response into a native JavaScript object. We use jQuery's $.each() to loop through the array of characters, and append a list item for each entry to the DOM.


Search JavaScript Objects

You can easily add custom search functionality to arrays of JavaScript objects (often loaded via AJAX/JSON) with a simple reusable function.

Steps

<html>
<head>
  <title>Search JavaScript Objects</title>
  <script src="jquery.min.js"></script>
  <script>
  // Sample dataset of people
  const people = [
    {
      title: "Mr",
      firstname: "John",
      lastname: "Doe"
    },
    {
      title: "Mrs",
      firstname: "Jane",
      lastname: "Doe"
    },
    {
      title: "Sir",
      firstname: "Johnathan",
      lastname: "Williams"
    },
    {
      title: "Sir",
      firstname: "Edward",
      lastname: "Tailor"
    }
  ];

  // Recursive search function
  function searchObjects(property, targetValue, inputObject) {
    let matches = [];
    for (let key in inputObject) {
      if (typeof inputObject[key] === 'object') {
        matches = matches.concat(searchObjects(property, targetValue, inputObject[key]));
      } else if (key === property && inputObject[key] === targetValue) {
        matches.push(inputObject);
      }
    }
    return matches;
  }

  // Usage: find all people with title "Sir"
  $(function(){
    const results = searchObjects("title", "Sir", people);
    console.log(results);
  });
  </script>
</head>
<body>
  Open the browser console to view search results
</body>
</html>

How it works

The searchObjects() function takes three arguments: the property name to search, the value to match, and the object/array to search. It recursively iterates through every property of the input object. If it finds a property that matches the name and value, it adds the current object to the matches array, which is returned when iteration is complete. This works for nested objects of any depth.


Sort JavaScript Objects

Sorting arrays of objects by a specified property is easy with a reusable sort function that works with JavaScript's native sort() method.

Steps

// Sample dataset
const people = [
  {
    title: "Mrs",
    firstname: "Jane",
    lastname: "Doe"
  },
  {
    title: "Sir",
    firstname: "Johnathan",
    lastname: "Williams"
  },
  {
    title: "Mr",
    firstname: "John",
    lastname: "Andrews"
  },
  {
    title: "Sir",
    firstname: "Edward",
    lastname: "Tailor"
  }
];

// Reusable sort function
function sortByProperty(property) {
  return function(a, b) {
    if (a[property] === b[property]) return 0;
    return a[property] > b[property] ? 1 : -1;
  }
}

// Usage: sort array by lastname
people.sort(sortByProperty("lastname"));
console.log(people);

How it works

JavaScript's native sort() method accepts a comparison function that takes two array elements as arguments and returns a value indicating their order. Our sortByProperty function wraps the comparison function, letting you specify which property to sort by. The outer function returns a comparison function that has access to the specified property via closure, creating a reusable sort utility that works for any object array.


Cache JSON and AJAX Responses

Caching responses reduces the number of unnecessary requests to your server, speeding up your application for repeat actions.

Steps

// Global cache storage
let responseCache = [];

$(function(){
  $('.load-data-btn').click(function(){
    // Only send request if cache is empty
    if (responseCache.length === 0) {
      $.ajax({
        url: '/get-people.php',
        method: 'GET'
      }).done(function(data){
        responseCache = data;
        renderList(data);
      });
    } else {
      // Use cached data directly
      renderList(responseCache);
    }
  });
});

function renderList(data) {
  $('#people-container').empty();
  $.each(data, function(key, value){
    $('#people-container').append("<li>#${key} ${value.firstname} ${value.lastname}</li>");
  });
}

How it works

We store cached responses in a global array. When a user clicks the load button, we check if the data already exists in the cache. If it doesn't, we send an AJAX request and store the result in the cache for future use. If it does exist, we use the cached data immediately, avoiding an unnecessary network request. This approach is ideal for static data that doesn't change often.


Build a Full-Text Search Feature

You can create a fast client-server search feature with jQuery, PHP and MySQL with just a few lines of code.

Steps

  1. First, create your database and table:
CREATE DATABASE IF NOT EXISTS jquery_demo;
USE jquery_demo;

CREATE TABLE IF NOT EXISTS products (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(128) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `products` (`id`, `title`) VALUES
(1, 'Ruler'),
(2, 'Pencil'),
(3, 'Pen'),
(4, 'Eraser'),
(5, 'Pencil Sharpener');
  1. Create db-config.php for database connection:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'jquery_demo';

$db = new mysqli($db_host, $db_user, $db_pass);
$db->select_db($db_name);
if($db->connect_errno > 0){
  die('Database connection failed: ' . $db->connect_error);
}
?>
  1. Create search-endpoint.php:
<?php
$response = new stdClass;
$response->success = false;
$response->results = [];
$response->error = null;

if (isset($_POST['search_term'])) {
  require_once('db-config.php');
  $search_term = $db->real_escape_string($_POST['search_term']);
  $query = "SELECT * FROM products WHERE title LIKE '%{$search_term}%'";
  $result = $db->query($query);

  if (!$result) {
    $response->error = "Search failed: " . $db->error;
  } else {
    while ($row = $result->fetch_assoc()) {
      $response->results[] = [
        'id' => $row['id'],
        'title' => $row['title']
      ];
    }
    $response->success = true;
  }
}

header("Content-Type: application/json; charset=UTF-8");
echo json_encode($response);
?>
  1. Create the frontend HTML search-demo.html:
<html>
<head>
  <title>Search Demo</title>
  <script src="jquery.min.js"></script>
  <script src="search.js"></script>
  <link rel="stylesheet" href="search.css" />
</head>
<body>
  <div id='container'>
    <div class='search-box'>
      <div class='header'>
        <h1>Product Search</h1>
        <input type='text' id='search-input' />
        <button id='search-btn'>Search</button>
      </div>
      <div id='results-area'>
        <div class="loading-wrap">
          <div class="loading-text">Loading...</div>
        </div>
        <ul id='results-list'></ul>
      </div>
    </div>
  </div>
</body>
</html>
  1. Add CSS search.css:
@import url(http://fonts.googleapis.com/css?family=Denk+One);
body {
  font-family: 'Denk One', sans-serif;
}
#container {
  width: 500px;
  margin: 125px auto auto auto;
  border: solid 1px #CCC;
  box-shadow: 0 0 10px #CCC;
  border-radius: 5px;
  background-color: #FFF;
}
.search-box .header {
  margin: 25px;
  text-align: center;
}
.search-box .header input {
  width: 350px;
}
#results-area {
  min-height: 200px;
}
.loading-text {
  text-align: center;
  line-height: 30px;
  display: none;
}
.loading-wrap {
  height: 30px;
}
#results-list {
  margin: 0;
  padding: 0;
  list-style: none;
}
#results-list li {
  line-height: 30px;
  border-bottom: solid 1px #CCC;
  padding: 5px 5px 5px 10px;
  color: #333;
}
#results-list li:last-child {
	border: none;
}
#results-list .no-results {
  text-align: center;
  font-weight: bold;
}
  1. Add jQuery code search.js:
$(function(){
  $('#results-list').hide();
  $('#search-btn').click(function() {
    runSearch();
  });
  $('#search-input').keydown(function(e){
    if(e.keyCode === 13){
      runSearch();
    }
  });
});

function runSearch() {
  const searchText = $('#search-input').val();
  $('#results-list').hide();
  $.ajax({
    url: '/search-endpoint.php',
    type: 'POST',
    data: {
      'search_term': searchText
    },
    beforeSend: function(){
      $('.loading-text').fadeIn();
    },
    success: function(data) {
      $('.loading-text').fadeOut();
      if (data.success) {
        $('#results-list').empty();
        if(data.results.length > 0) {
          $.each(data.results, function(){
            $('#results-list').append("<li>" + this.title + "</li>");
          });
        } else {
          $('#results-list').append("<li class='no-results'>No products found matching your search</li>");
        }
        $('#results-list').fadeIn();
      } else {
        alert(data.error);
      }
    }
  });
}

This gives you a fully functional search feature that matches search terms against product titles in your MySQL database, with loading states and error handling.


Build an Autocomplete Suggestion Feature

Autocomplete speeds up user input by providing suggestions as the user types. You can build a custom one from scratch using the same search backend you created for the full search feature.

Steps

  1. Reuse the search-endpoint.php, database, and db-config.php from the previous search recipe.
  2. Create the frontend HTML autocomplete-demo.html:
<html>
<head>
  <title>Autocomplete Demo</title>
  <script src="jquery.min.js"></script>
  <script src='autocomplete.js'></script>
  <link href='autocomplete.css' rel="stylesheet" />
</head>
<body>
  <div id='container'>
    <div class='autocomplete-container'>
      <div class='header'>
        <h1>Product Search</h1>
      </div>
      <div class="input-wrapper">
        <input type='text' id='search-input' />
        <ul class="suggestion-list"></ul>
      </div>
    </div>
  </div>
</body>
</html>
  1. Add CSS autocomplete.css:
@import url(http://fonts.googleapis.com/css?family=Denk+One);
body {
  font-family: 'Denk One', sans-serif;
}
#container {
  width: 500px;
  margin: 125px auto auto auto;
  border: solid 1px #CCC;
  box-shadow: 0 0 10px #CCC;
  border-radius: 5px;
  background-color: #FFF;
}
.autocomplete-container .header {
  margin: 25px;
  text-align: center;
}
.input-wrapper input {
  width: 440px;
}
.input-wrapper {
  position: relative;
  padding: 25px;
}
.suggestion-list {
  position: absolute;
  width: 424px;
  background-color: #f1f1f1;
  margin: 0;
  left: 25px;
  top: 50px;
  z-index: 100;
  display: none;
  list-style: none;
  padding: 10px;
}
.suggestion-list li {
  line-height: 30px;
  border-bottom: 1px solid #ddd;
}
.suggestion-list li:last-child {
  border-bottom: none;
}
.suggestion-list .suggestion-item {
  cursor: pointer;
  color: #333;
  text-decoration: none;
  display: block;
}
  1. Add JavaScript autocomplete.js:
$(function(){
  $('#search-input').keyup(function(e){
    if ($('#search-input').val().length > 2) {
      $('.suggestion-list').show();
      loadSuggestions();
    } else {
      $('.suggestion-list').hide();
    }
  });
  $('.autocomplete-container').on("click", ".suggestion-item", function(){
    $('#search-input').val($(this).html());
    $('.suggestion-list').hide();
  });
});

function loadSuggestions() {
  const searchText = $('#search-input').val();
  $('.suggestion-list').empty();
  $.ajax({
    url: '/search-endpoint.php',
    type: 'POST',
    data: {
      'search_term': searchText
    },
    beforeSend: function(){
      $('.suggestion-list').append("<li class='loading'>Loading...</li>");
    },
    success: function(data) {
      if (data.success) {
        $('.suggestion-list').empty();
        if(data.results.length > 0) {
          $.each(data.results, function(){
            $('.suggestion-list').append("<li><a href='#' class='suggestion-item'>" + this.title + "</a></li>");
          });
        } else {
          $('.suggestion-list').append("<li class='no-results'>No suggestions available</li>");
        }
      } else {
        alert(data.error);
      }
    }
  });
}

This creates a working autocomplete feature that loads suggestions after the user types more than 2 characters, and lets the user click a suggestion to fill the input.


Wait for Multiple AJAX Requests to Complete

By default, AJAX requests run asynchronously, so code after the request will run before the request completes. To run code only after multiple requests finish, use jQuery's $.when() method.

Steps

  1. Create two slow PHP endpoints to simulate long-running requests: slow-request-1.php:
<?php
for ($i = 1; $i <= 2; $i++) {
  sleep(1);
}
echo "First request completed.";
?>

slow-request-2.php:

<?php
for ($i = 1; $i <= 5; $i++) {
  sleep(1);
}
echo "Second request completed.";
?>
  1. Create the demo HTML when-demo.html:
<html>
<head>
  <title>Wait for AJAX Completion Demo</title>
  <script src="jquery.min.js"></script>
  <script src="when-demo.js"></script>
</head>
<body>
  <button class="trigger-btn">Load Both Requests</button>
  <div class="output"></div>
</body>
</html>
  1. Add JavaScript when-demo.js:
$(function(){
  $('.trigger-btn').click(function(){
    $.when(sendFirstRequest(), sendSecondRequest()).done(function(res1, res2){
      $('.output').append("<p>Both AJAX requests completed successfully!</p>");
    });
  });
});

function sendFirstRequest() {
  return $.ajax({
    url: '/slow-request-1.php',
    method: 'GET'
  }).done(function(data){
    $('.output').append("<p>" + data + "</p>");
  });
}

function sendSecondRequest() {
  return $.ajax({
    url: '/slow-request-2.php',
    method: 'GET'
  }).done(function(data){
    $('.output').append("<p>" + data + "</p>");
  });
}

How it works

$.when() accepts multiple deferred objects (like AJAX requests) as arguments, and the .done() callback only runs after all deferred objects resolve. This lets you run code that depends on multiple AJAX requests completing, without turning off asynchronous behavior (which can cause browser freezing for slow requests).


jQuery Visual Effects

jQuery provides built-in methods to add simple, smooth visual effects to your intreface, improving user experience.

Slide Elements In and Out

Sliding effects are commonly used for accordions, dropdowns, and expanding sections. jQuery provides slideUp() and slideDown() methods to animate element height.

Example Code

<html>
<head>
  <script src="jquery.min.js"></script>
  <script src="slide-demo.js"></script>
  <link rel="stylesheet" href="slide-demo.css" />
  <title>Slide Effect Demo</title>
</head>
<body>
  <div class="container">
    <div class="controls">
      <button id="slide-up-btn">Slide All Up</button>
      <button id="slide-down-btn">Slide All Down</button>
    </div>
    <div class="box red"></div>
    <div class="box green"></div>
    <div class="box blue"></div>
    <div class="box orange"></div>
  </div>
</body>
</html>

slide-demo.css:

.container {
  width: 530px;
  height: 190px;
  margin: 50px auto auto auto;
  background-color: #E1E1E1;
  padding: 10px;
}
.box {
  width: 125px;
  height: 125px;
  float: left;
  margin-right: 10px;
}
.box:last-child {
  margin-right: 0;
}
.controls {
  background-color: #333;
  margin-bottom: 10px;
  text-align: center;
  padding: 10px;
}
.controls button {
  height: 35px;
}
.red { background-color: red; }
.green { background-color: green; }
.blue { background-color: blue; }
.orange { background-color: orange; }

slide-demo.js:

$(function(){
  $('#slide-up-btn').click(function(){
    $('.red').slideUp(4000);
    $('.green').slideUp(3000);
    $('.blue').slideUp(2000);
    $('.orange').slideUp(1000);
  });
  $('#slide-down-btn').click(function(){
    $('.red').slideDown(4000);
    $('.green').slideDown(3000);
    $('.blue').slideDown(2000);
    $('.orange').slideDown(1000);
  });
});

The first parameter to slideUp()/slideDown() is the duration of the animation in milliseconds, letting you create staggered waterfall effects like this example.


Hide and Show Elements

jQuery provides simple hide() and show() methods to toggle element visibility directly without animation. They modify the element's display CSS property, hiding it from the layout completely when hidden.

$('.show-btn').click(function(){
  $('.target-text').show();
});
$('.hide-btn').click(function(){
  $('.target-text').hide();
});

Fade Elements In and Out

For smoother transitions, use fade effects to adjust element opacity when showing or hiding.

Example: Fade In New List Items

<html>
<head>
  <script src="jquery.min.js"></script>
  <script src="fade-demo.js"></script>
  <link rel="stylesheet" href="fade-demo.css" />
  <title>Fade Effect Demo</title>
</head>
<body>
  <div class="container">
    <div class="input-area">
      <label>New Item:</label>
      <input type="text" id="new-item-input" />
      <button id="add-item-btn">Add Item</button>
    </div>
    <ol class="item-list"></ol>
  </div>
</body>
</html>
$(function(){
  $('#add-item-btn').click(function(){
    const itemText = $('#new-item-input').val();
    if (itemText.length > 0) {
      const newItem = $("<li>" + itemText + "</li>").hide();
      $('.item-list').append(newItem);
      newItem.fadeIn(500);
      $('#new-item-input').val("");
    }
  });
});

jQuery also provides fadeToggle() to automatically switch between visible and hidden, and fadeTo() to fade to a specific opacity value between 0 and 1.


Toggle Effects

All common jQuery effects have a toggle variant that automatically switches between the opposite states, so you don't have to check the current state manually.

$('.toggle-fade-btn').click(function(){
  $('.target-element').fadeToggle(400);
});

$('.toggle-slide-btn').click(function(){
  $('.target-element').slideToggle(400);
});

$('.toggle-hide-btn').click(function(){
  $('.target-element').toggle();
});

fadeToggle() will fade out visible elements and fade in hidden elements, all with one line of code.


Stop and Finish Running Effects

jQuery lets you stop currently running animations, which is useful for preventing queued animations from running after a user interacts multiple times.

$('#start-btn').click(function(){
  $('.target-box').slideToggle(2000, function(){
    $('.output').append("<li>Slide effect completed</li>");
  });
});

$('#stop-btn').click(function(){
  $('.target-box').stop();
});

$('#finish-btn').click(function(){
  $('.target-box').finish();
});
  • stop() halts the animation immediately at its current state, and does not run the completion callback.
  • finish() jumps directly to the final state of the animation, completes it, and runs the completion callback.

Chaining Multiple Effects

jQuery lets you chain multiple effects sequentially, so they run one after another automatically.

$('#start-animation-btn').click(function(){
  $('.animated-box')
    .fadeOut(500)
    .fadeIn(500)
    .slideUp(500)
    .slideDown(500)
    .fadeTo(1000, 0.2)
    .fadeTo(1000, 1);
});

All chained effects run in order, creating a seamless sequence of animations with very clean code.


Build a Basic Image Gallery

You can build a fully functional responsive image gallery with jQuery effects in just a few lines of code.

Steps

  1. Create the HTML:
<html>
<head>
  <script src="jquery.min.js"></script>
  <script src="gallery.js"></script>
  <link rel="stylesheet" href="gallery.css" />
  <title>jQuery Image Gallery</title>
</head>
<body>
  <div class="gallery" data-thumb-width="150">
    <div class="main-view">
      <img src="images/img1.jpg" />
      <img src="images/img2.jpg" />
      <img src="images/img3.jpg" />
      <img src="images/img4.jpg" />
      <img src="images/img5.jpg" />
      <img src="images/img6.jpg" />
      <img src="images/img7.jpg" />
      <img src="images/img8.jpg" />
    </div>
    <div class="thumb-container">
      <a href="#" class="nav-arrow left-arrow" data-direction="left"><i class="icon-left"></i></a>
      <a href="#" class="nav-arrow right-arrow" data-direction="right"><i class="icon-right"></i></a>
      <div class="thumbs"></div>
    </div>
  </div>
</body>
</html>

Update the image src attributes to point to your images.

  1. Add CSS:
body {
  margin: 0;
  padding: 0;
  background-color: #333;
}
.gallery {
  width: 600px;
  margin: 50px auto auto auto;
  position: relative;
}
.gallery .main-view {
  height: 450px;
  margin-bottom: 10px;
  position: relative;
}
.gallery .main-view img {
  display: block;
  width: 100%;
  position: absolute;
  left: 0;
  top: 0;
}
.gallery .thumb-container {
  overflow: hidden;
}
.gallery .thumbs {
  height: 120px;
  white-space: nowrap;
  text-align: center;
}
.gallery .thumbs a {
  display: inline-block;
  opacity: 0.5;
  transition: opacity 0.5s ease-in-out;
}
.gallery .thumbs a:hover {
  opacity: 1;
}
.gallery .nav-arrow {
  width: 50px;
  height: 50px;
  background-color: #000;
  position: absolute;
  border-radius: 50%;
  bottom: 35px;
}
.gallery .nav-arrow.disabled {
  background-color: #252525;
}
.gallery .left-arrow { left: -60px; }
.gallery .right-arrow { right: -60px; }
.gallery .icon-right {
  width: 0;
  height: 0;
  border-top: 12px solid transparent;
  border-bottom: 12px solid transparent;
  border-left: 12px solid #1a1a1a;
  position: absolute;
  right: 16px;
  top: 13px;
}
.gallery .icon-left {
  width: 0;
  height: 0;
  border-top: 12px solid transparent;
  border-bottom: 12px solid transparent;
  border-right:12px solid #1a1a1a;
  position: absolute;
  right: 21px;
  top: 13px;
}
  1. Add jQuery code:
let allImages;
let thumbWidth;
$(function(){
  thumbWidth = $('.gallery').data("thumb-width");
  allImages = $('.gallery').find('img');

  // Generate thumbnails
  $.each(allImages, function(index, img){
    $(img).addClass("img-" + index);
    $('.gallery .thumbs').append(`<a href='#' data-index='${index}' class='thumb'><img src='${$(img).attr("src")}' width='${thumbWidth}' height='120' border='0' /></a>`);
  });

  updateNavButtons();

  // Scroll thumbs
  $('.nav-arrow').click(function(){
    const $arrow = $(this);
    if (!$arrow.hasClass('disabled')) {
      $arrow.addClass('disabled');
      let scrollChange = "-=";
      if ($arrow.data("direction") == "left") {
        scrollChange = "+=";
      }
      $('.thumbs').animate({
        marginLeft: scrollChange + thumbWidth + "px"
      }, "fast", function(){
        $arrow.removeClass('disabled');
        updateNavButtons();
      });
    }
  });

  // Show selected image
  $('.gallery').on("click", ".thumb", function(){
    const selectedThumb = $(this);
    const targetImage = $('.img-' + selectedThumb.data('index'));
    $.each(allImages, function(index, img){
      if (!$(img).hasClass('img-' + selectedThumb.data('index'))) {
        $(img).hide();
      }
    });
    if (targetImage.css('display') != 'block') {
      targetImage.fadeIn();
    }
  });
});

function updateNavButtons() {
  const thumbs = $('.thumbs');
  const currentMargin = parseInt(thumbs.css("margin-left"));
  const totalThumbWidth = allImages.length * thumbWidth;
  if (currentMargin >= 0) {
    $('.left-arrow').addClass('disabled');
  } else {
    $('.left-arrow').removeClass('disabled');
  }
  if ((currentMargin * -1) >= (totalThumbWidth - thumbs.width() / 2)) {
    $('.right-arrow').addClass('disabled');
  } else {
    $('.right-arrow').removeClass('disabled');
  }
}

This creates a gallery with scrollable thumbnails, smooth fade transitions between main images, and disabled navigation buttons when you reach the end of the thumbnail list.


Create a Pulsing Button to Draw Attention

You can create a subtle blinking/pulsing button effect with chained fadeTo calls to draw user attention to important actions.

Example

<html>
<head>
  <script src="jquery.min.js"></script>
  <script src="blink-demo.js"></script>
  <link rel="stylesheet" href="blink-demo.css" />
  <title>Pulsing Button Demo</title>
</head>
<body>
  <div class="container">
    <h1>Newsletter Signup</h1>
    <p>Enter your email below to get our monthly updates.</p>
    <form>
      <input type="text" class="email-input" name="email" placeholder="Your Email Address" />
      <br />
      <button class="signup-btn">Sign Up Now</button>
    </form>
  </div>
</body>
</html>
$(function(){
  $('.email-input').on('focus', function(){
    $('.signup-btn').fadeTo(300, 0.1).fadeTo(300, 1);
  })
});

When the user focuses the email input, the sign up button pulses to draw attention to the next step.


Remove Elements with Animation

You can animate the removal of DOM elements (like list items or table rows) with a simple fade out effect, creating a smoother user experience.

Example: User Management Table

<html>
<head>
  <script src="jquery.min.js"></script>
  <script src="remove-demo.js"></script>
  <link rel="stylesheet" href="remove-demo.css" />
  <title>Animated Element Removal Demo</title>
</head>
<body>
  <div class="container">
    <h1>User Management</h1>
    <table width="100%" id="user-table">
      <thead>
        <tr>
          <th>Username</th>
          <th>Email</th>
          <th>Full Name</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>jd101</td>
          <td>j.doe@example.com</td>
          <td>John Doe</td>
          <td><button class="delete-btn">Delete</button></td>
        </tr>
        <tr>
          <td>msmith17</td>
          <td>jane.smith@example.com</td>
          <td>Jane Smith</td>
          <td><button class="delete-btn">Delete</button></td>
        </tr>
        <tr>
          <td>twilson22</td>
          <td>tom.wilson@example.com</td>
          <td>Tom Wilson</td>
          <td><button class="delete-btn">Delete</button></td>
        </tr>
      </tbody>
    </table>
  </div>
</body>
</html>
$(function(){
  $('#user-table').on("click", ".delete-btn", function(){
    const confirmDelete = confirm("Are you sure you want to delete this user?");
    if (confirmDelete) {
      $(this).closest('tr').fadeOut(function(){
        $(this).remove();
      });
    }
  });
});

When the user confirms deletion, the table row fades out smoothly before being removed from the DOM.

Tags: jQuery

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.