DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How To Make a Windows Keylogger By Yourself
  • Generic and Dynamic API: MuleSoft
  • Microservices With .NET Core: Building Scalable and Resilient Applications
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript

Trending

  • MCP Servers: The Technical Debt That Is Coming
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • The Future of Java and AI: Coding in 2025
  • Monolith: The Good, The Bad and The Ugly
  1. DZone
  2. Coding
  3. JavaScript
  4. Exploring Intercooler.js: Simplify AJAX With HTML Attributes

Exploring Intercooler.js: Simplify AJAX With HTML Attributes

Discover how Intercooler.js makes AJAX simple using HTML attributes, no heavy JavaScript needed. A smart and lightweight alternative for dynamic pages.

By 
Nagappan Subramanian user avatar
Nagappan Subramanian
DZone Core CORE ·
May. 21, 25 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
2.1K Views

Join the DZone community and get the full member experience.

Join For Free

Intercooler.js is a lightweight JavaScript library that enables developers to add AJAX functionality to their web applications with minimal effort. Inspired by HTML's simplicity, it allows the use of HTML attributes to handle dynamic updates instead of writing extensive JavaScript code. This library is ideal for developers who want the power of AJAX without diving into complex frameworks like React or Angular.

Note: While Intercooler.js is still supported, its successor, htmx, offers additional features and enhanced browser capabilities.

Why Choose Intercooler.js?

  • Ease of Use: Fetching dynamic content and updating an HTML element can be as simple as adding the ic-get-from attribute to an element.
  • Lightweight: At around 15KB, Intercooler.js ensures your web app remains fast and responsive.
  • Framework-Free: It integrates seamlessly into existing projects without relying on external frameworks.
  • HTML-Enhanced: It extends HTML semantics using attributes like ic-get-from, ic-post-to, and ic-trigger-on, transforming static HTML into dynamic, interactive interfaces.

Key Features of Intercooler.js

  • Simplified AJAX Requests: Use ic-get-from and ic-post-to attributes to fetch or send data.
  • Partial Page Updates: Refresh specific parts of the web page without reloading the whole page.
  • Event Binding: Trigger updates based on user interactions like clicks or mouseovers via ic-trigger-on.
  • Declarative UI: Focus on clean HTML while Intercooler.js handles JavaScript logic behind the scenes.

Getting Started

1. Download Intercooler.js

Start by visiting the official https://intercoolerjs.org/ website or a trusted CDN repository. You can either download the library or use a CDN link.

2. Include Intercooler.js in Your HTML

HTML
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/intercooler/1.2.3/intercooler.min.js"></script>


Alternatively, if you downloaded the file, include it like this:

HTML
 
<script src="path/to/intercooler.min.js"></script>


3. Add the Required Dependency:

Intercooler.js depends on jQuery, so ensure jQuery is included before Intercooler.js:

HTML
 
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


4. Set Up Your HTML Structure

Here's a simple example to demonstrate how Intercooler.js works:

HTML
 
OSZAR »
" data-lang="text/html">
<!DOCTYPE html>

<html>

<head>

    <title>Intercooler.js Setup</title>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/intercooler/1.2.3/intercooler.min.js"></script>

</head>

<body>

    <h1>Welcome to Intercooler.js</h1>

    <button ic-get-from="/data-endpoint" ic-target="#content">

        Load Content

    </button>

    <div id="content">

        <!-- Content loaded here -->

    </div>

</body>

</html>


Setup: Here, we have to import both jQuery (a required dependency for Intercooler.js) and the Intercooler.js library using <script> tags.

Button with ic-get-from: The button element has the attribute ic-get-from="/data-endpoint". 

This tells Intercooler.js to send a GET request to the /data-endpoint URL when the button is clicked.

The response from this request will be loaded into the element specified by ic-target="#content".

Content Target: The <div id="content"> acts as a container where the returned data will be dynamically inserted.

Server Requirement: For this example to work, you need to have a server running and serving the /data-endpoint URL. This URL should respond with HTML content that will be inserted into the #content div.

How to Run Intercooler.js

To run the Intercooler.js example, here’s a detailed guide that walks you through every step of setting up and running your code:

Prerequisites

Before proceeding, ensure you have the following:

  • A Web Browser: Any modern browser like Chrome, Firefox, or Edge should work.

  • A Simple Local Server: Browsers enforce certain security restrictions when loading files via the file:// protocol. Using a server helps avoid these issues.

Local Server Options:

  • Using Python: Python version 3.x comes with a built-in HTTP server.

  • Using Node.js: Install a lightweight server like http-server or live-server.

  • Other Tools: Tools like Visual Studio Code Live Server Extension can work too.

 Running a Local Server

  • Using Node.js (http-server)

Install http-server globally (if not already installed): npm install -g http-server

Start the server: http-server -p 8080

Open your browser and navigate to http://localhost:8000 (or the port shown in the terminal).


  • Using Python (http-server)

Navigate to the project folder in your terminal: cd path/to/project

Start the server:

For Python 3.x: python -m http.server 8080

If you’re using Python 2.x: python -m SimpleHTTPServer 8080

Open the browser and go to http://127.0.0.1:8080


  • Using VS Code Live Server Extension
    • Open the project folder in Visual Studio Code.
    • Install the Live Server extension (search for it in the Extensions Marketplace).
    • Right-click on index.html and select Open with Live Server.
    • The file will open in your default browser.
  • Verify Your server.js File

If you're using Node.js with a server.js file to run your project, here's a step-by-step guide to ensure your setup works with Intercooler.js.

Make sure your server.js file sets up a server and serves your files correctly. A basic example using Node.js and the express library might look like this:


JavaScript
 
const express = require('express');

const app = express();

const port = 8080;



// Serve static files (like index.html, scripts, etc.)

app.use(express.static(__dirname));



// Handle your /data-endpoint route

app.get('/data-endpoint', (req, res) => {

  res.send('<p>This content was loaded dynamically!</p>');

});



// Start the server

app.listen(port, () => {

  console.log(`Server is running on http://127.0.0.1:${port}`);

});


If you're using express, make sure it's installed. Run the following command in your project directory: 

  • npm install express
  • Start Your Server: node server.js
  • Run the server: node server.js

Open your browser and navigate to http://localhost:8080.

Web Development Use Cases

Let's explore Intercooler.js with some web development use cases. We will take you through the code, explanation of each examples. 

Example 1. Employee Joining Form

HTML
 
<head>

  <!-- Include jQuery -->

  

  <!-- Include Intercooler.js -->



</head>

<body>

    <!-- Form Submission -->

    <form ic-post-to="/submit-employee" ic-target="#form-response">

      <div class="form-group">

              <input type="text" name="name" required>

             <input type="email" name="email" required>

<input type="tel" name="mobile" pattern="[0-9]{10}" required>

<input type="number" name="experience" min="0" required>

      </div>

<div id="form-response" class="box">Form response will appear here.</div>



    <div ic-get-from="/server-time" ic-poll="3s" class="box">Fetching server time...</div>

    </form>

    <!-- Form Response -->

  </div>

</html>


The form collects employee information such as Name, Email, Mobile Number, Qualification, and Experience. The form uses built-in validation (required, pattern, min) for data integrity.

The form uses the ic-post-to attribute, which sends the form data to /submit-employee when submitted. The response from the server is dynamically displayed in the <div id="form-response">.

A bonus feature displays the live server time, which is updated every 3 seconds using the ic-get-from attribute.


JavaScript
 
app.post("/submit-employee", (req, res) => {

  const { name, email, mobile, qualification, experience } = req.body;

 

  // Validate required fields

  if (!name || !email || !mobile || !qualification || experience === undefined) {

    return res.status(400).send("All fields are required!");

  }

});



// Handle live server time

app.get("/server-time", (req, res) => {

  res.send(new Date().toLocaleTimeString());

});


How It Works

  • Client-Side Interaction: Users fill in the form, and the ic-post-to attribute triggers a dynamic POST request to the server.

  • Server-Side Processing: The backend validates the input and responds with a success message.

  • Real-Time Updates: The server time is fetched and updated automatically, demonstrating live polling with Intercooler.js.

Example 2: Button Animation

The second example in this series focuses on Button Animations. This interactive and visually appealing implementation showcases how Intercooler.js can be leveraged to create dynamic UI effects with minimal effort. Various animation effects, like Bounce, Shake, Zoom, Flip, Spin, and Fade, add an engaging touch to buttons.

Here’s an example of the HTML Button Setup:

HTML
 
<button id="bounceBtn" class="btn" ic-get-from="/api/animation" ic-trigger="click" ic-target="#bounceBtn" ic-response-type="json" ic-transition-duration="1000ms">

        Bounce

      </button>

      <button id="shakeBtn" class="btn" ic-get-from="/api/animation" ic-trigger="click" ic-target="#shakeBtn" ic-response-type="json" ic-transition-duration="1000ms">

        Shake

      </button>


The CSS Animation for Bounce:


CSS
 
@keyframes bounce {



      0%,

      100% {

        transform: translateY(0);

      }



      50% {

        transform: translateY(-10px);

      }

    }



    #bounceBtn.ic-transitioning {

      animation: bounce 1s ease-in-out;

    }

  @keyframes shake {

      0% {

        transform: skewX(-10deg);

      }

      25%,

      75% {

        transform: skewX(10deg);

      }



      50% {

        transform: skewX(-10deg);

      }



      100% {

        transform: skewX(0);

      }

    }



    #shakeBtn.ic-transitioning {

      animation: shake 1s ease-out;

    }


And here’s a Backend Response:


JavaScript
 
app.get('/api/animation', (req, res) => {

    const elementId = req.query['ic-element-id'];

    if (elementId === "bounceBtn")

      res.status(200).send("Bounce Off");

    else if (elementId === "shakeBtn")

      res.status(200).send("I am shaking!");

});


How It Works

  • Clicking a button sends an AJAX-like request to the server using Intercooler.js..

  • The server identifies the button through its ic-element-id and returns an appropriate response.

  • CSS animations are triggered dynamically when the response is received

Example 3: Infinite Scrolling Weather Data

The third example in this series showcases the concept of Infinite Scrolling, integrated seamlessly with weather data. This interactive implementation dynamically fetches and appends weather records to a table as the user scrolls, ensuring a smooth browsing experience.

Infinite Scrolling with Intercooler.js:

  • The ic-append-from attribute dynamically loads additional weather data when the user scrolls into view of the "Loading more data..." row.

  • The ic-trigger-on="scrolled-into-view" ensures data fetching is triggered at the right moment, enhancing performance.

  • The table updates on demand without requiring a full-page refresh. Weather data includes Time, Temperature, Humidity, and Wind Speed.

  • A spinner (<i> tag styled with Font Awesome) provides visual feedback during data fetching, triggered by ic-indicator="#indicator".

  • The backend fetches weather data from the Open-Meteo API and slices it based on user scroll position (start and limit query parameters).

  • A 3-second delay is introduced using the ic-beforeSend event to mimic realistic server processing time.

  • Geolocation: Retrieves the user's latitude and longitude using navigator.geolocation.

  • Dynamic Data Appending: Appends weather data rows to the table without reloading the page.


HTML
 
<tbody id="weatherTableBody">

  <tr ic-append-from="/weather?start=0&limit=10" ic-trigger-on="scrolled-into-view" ic-target="#weatherTableBody" ic-indicator="#indicator">

    <td>Loading more data...</td>

    <td></td>

    <td></td>

    <td></td>

  </tr>

</tbody>


The server slices the weather data based on start and limit parameters provided by the client.

  • Integrates Intercooler.js for infinite scrolling and jQuery for appending geolocation to requests.

JavaScript
 
<script>

    var lat,long;

    navigator.geolocation.getCurrentPosition(function(position) {

      console.log(position.coords.latitude + ', ' + position.coords.longitude);

      lat = position.coords.latitude; long = position.coords.longitude;

    });

    $(document).on('beforeAjaxSend.ic', function(event, ajaxSetup, elt){

      console.log("before ajax send events",  ajaxSetup.url);

      ajaxSetup.url += "&lat=" + lat + "&long=" + long;

      console.log("before ajax send events",  ajaxSetup.url);

    });

   

  </script>



app.get('/weather', async (req, res) => {

  const start = parseInt(req.query.start) || 0;

  const limit = parseInt(req.query.limit) || 10;

  const response = await axios.get(API_URL);

  let html = '';

  for (let i = start; i < start + limit; i++) {

    html += `<tr><td>${response.data.hourly.time[i]}</td>

    <td>${response.data.hourly.temperature_2m[i]}</td>

    <td>${response.data.hourly.relative_humidity_2m[i]}</td>

    <td>${response.data.hourly.wind_speed_10m[i]}</td></tr>`;

  }

  res.send(html);

});



}


How It Works

  1. The user's coordinates are captured (lat, long) using the browser's navigator.geolocation

  2. When the page loads, the first 10 rows of weather data are fetched from the /weather endpoint.

  3. When the last row of the table comes into view (ic-trigger-on="scrolled-into-view"), more rows are fetched dynamically.

  4. Based on the start and limit query parameters, the backend slices the data and appends rows until the dataset is exhausted.


Example 4: Understanding Intercooler.js Events

In this example, we explore how Intercooler.js events like ic-beforeSend, ic-success, and ic-error can be utilized to enhance form interactions with dynamic visual and functional feedback.

ic-beforeSend Event:

  • Displays a loading spinner and disables the submit button while an AJAX request is being processed.

  • Ensures a smooth user experience during data submission.

ic-success Event:

  • Restores the button to its original state after successful submission.

  • Updates a target area (#responseMessage) with a success message dynamically received from the server.

ic-error Event:

  • Handles errors gracefully by restoring the button state and displaying error messages from the server.

Dynamic API Response:

  • The server simulates different outcomes (success, failure, error) based on user input, allowing for versatile testing of event behaviors.

Event listeners ensure smooth interaction and graceful error handling:

JavaScript
 
document.addEventListener('ic-beforeSend', function (e) {

  const button = e.target.querySelector('button[type="submit"]');

  button.dataset.originalContent = button.innerHTML;

  button.innerHTML = `<span class="loader"></span> Loading...`;

  button.disabled = true;

});



document.addEventListener('ic-success', function (e) {

  const button = e.target.querySelector('button[type="submit"]');

  button.innerHTML = button.dataset.originalContent;

  button.disabled = false;

  document.getElementById('responseMessage').innerHTML = `<div style="color: green;">${e.detail.response}</div>`;

});


Server Logic: The API dynamically responds based on user input,


JavaScript
 
app.post('/mock-api', (req, res) => {

  const { input } = req.body;

  if (input === 'success') {

    return res.status(200).send('Success! Data was processed correctly.');

  } else if (input === 'failure') {

    return res.status(400).send('Failure! Invalid input provided.');

  } else {

    return res.status(500).send('Error! Something went wrong.');

  }

});


How It Works

  1. The user submits a form, triggering an ic-beforeSend event to show a loading spinner.

  2. On server response:

    • Success: Displays a success message dynamically.

    • Failure/Error: Reverts the button and displays error feedback.

Example 5: Polling with Intercooler.js

In this example, we explore how to implement Polling using Intercooler.js to dynamically fetch weather updates at regular intervals without requiring user interaction. This real-time data fetching is both efficient and user-friendly.

Automatic Data Refresh:

  • The ic-poll="2s" attribute sets up polling every 2 seconds, ensuring the latest weather data is fetched automatically.

  • The ic-src="/poll_example" specifies the endpoint providing the updated weather information.

Trigger on Page Load:

  • The polling mechanism begins immediately when the page loads using ic-trigger-on="load", eliminating the need for manual initiation.

Geolocation Support:

  • Uses the browser's navigator.geolocation to capture the user's latitude and longitude.

  • Updates the ic-get-from URL dynamically to fetch data for the user's location.

Loading Indicator:

  • Shows a spinning icon (<i class="fas fa-sync-alt fa-spin">) while data is being fetched.

Backend Integration:

  • The server fetches real-time weather data from the Open-Meteo API to simulate real-time updates for the polling mechanism.

Polling Element in HTML: The element with ic-poll automatically triggers requests to fetch weather data every 2 seconds:


HTML
 
<span ic-poll="2s" ic-src="/poll_example" ic-trigger-on="load">

  Loading weather data...

</span>


The server fetches weather data and randomly selects a weather record to display:

JavaScript
 
app.get('/poll_example', async (req, res) => {

const response = await axios.get(`${BASE_API_URL}?latitude=${lat}& longitude=${long}¤t_weather=true`);

    const data = response.data.current_weather;

    if (!data) {

      throw new Error('Weather data unavailable');

    }



const weatherData = {

time: new Date().toLocaleTimeString(),

      temperature: data.temperature,

      humidity: data.relative_humidity || 'N/A',

      windSpeed: data.windspeed || 'N/A',

};

res.send(`

<span>

  <strong>Time:</strong> ${weatherData.time} <br>

  <strong>Temperature:</strong> ${weatherData.temperature}°C <br>

  <strong>Humidity:</strong> ${weatherData.humidity}% <br>

  <strong>Wind Speed:</strong> ${weatherData.windSpeed} km/h

</span>

`);

});


How It Works:

Initial Data Load:

  • When the page loads, the user's location is captured, or a default location is used.

  • The backend serves weather data for the specified latitude and longitude.

Real-Time Polling:

  • Intercooler.js repeatedly calls the /poll_example endpoint every 2 seconds (ic-poll="2s") to fetch fresh weather updates.

Frontend Updates:

  • The weather details (Time, Temperature, etc.) are dynamically updated in the container without requiring a page refresh.

Complete code example is available in github.

Conclusion

If we are developing simple web application project with few server interaction of server updates or use some external apis to store or fetch the data (like google apis), Intercooler.js would be best choice to integrate it easily.

AJAX API HTML HTTPS JavaScript Visual Studio Code Attribute (computing) Data (computing) Event Form (document)

Opinions expressed by DZone contributors are their own.

Related

  • How To Make a Windows Keylogger By Yourself
  • Generic and Dynamic API: MuleSoft
  • Microservices With .NET Core: Building Scalable and Resilient Applications
  • How to Create a Pokémon Breeding Gaming Calculator Using HTML, CSS, and JavaScript

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

OSZAR »