0

If I may pick your brain?

I'm working on a web development project where I need to implement filter buttons that update the content of a page without reloading it. I've written a JavaScript function that successfully creates and adds filter buttons to my page. However, currently, when these buttons are clicked, they redirect the user to a new URL, causing the page to reload. I want to modify this so that the content updates dynamically without a page refresh.

Here's the current code snippet:

(function() {
  'use strict';

  function createFilterButton(id, text, filterUrl) {
    let button = document.createElement('button');
    button.id = id;
    button.textContent = text;
    button.style.cssText = `
      background-color: black;
      color: white;
      text-transform: uppercase;
      padding: 10px 20px;
      margin-top: 10px;
      margin-right: 10px;
      margin-bottom: 15px;
      border: none;
      border-radius: 25px;
      cursor: pointer;
      font-size: 17px;
    `;
    button.addEventListener('click', function() {
      window.location.href = filterUrl;
    });
    return button;
  }

  if (window.location.pathname.includes('/collections/new-arrivals')) {
    const collectionTitle = document.querySelector('.collection__title');
    if(collectionTitle) {
        
          // Add the 'DENIM' button
      collectionTitle.insertAdjacentElement('afterend', createFilterButton('denimFilter', 'DENIM', '/collections/new-arrivals/latest-denim'));
        
           // Add the 'FAUX LEATHER' button
      collectionTitle.insertAdjacentElement('afterend', createFilterButton('fauxFilter', 'FAUX LEATHER', '/collections/new-arrivals/latest-faux-leather'));
        
      // Add the 'ALL' button
      collectionTitle.insertAdjacentElement('afterend', createFilterButton('allFilter', 'ALL', '/collections/new-arrivals'));
    
    }
  }
})();

I've been exploring and testing the use of the pushState and replaceState methods as part of my efforts to dynamically update the content on a webpage without a full page reload. Alongside this, I am also conducting research into whether Alpine.js could be a viable solution for my needs. My goal is to manipulate the browser's history, change the URL in the address bar to reflect the applied filters, and fetch and display new content.

Here's what I've done so far:

1.) Studying pushState and replaceState Methods

2.) Experimentation with History Manipulation: I attempted to integrate these methods into my existing JavaScript code. Specifically, replacing the window.location.href assignment in my button click event listener with a call to history.pushState or history.replaceState.

3.) Exploring Alpine.js: Concurrently, I am researching the potential of using Alpine.js. I believe its lightweight nature and declarative style might offer a simpler and more efficient way to handle dynamic content updates.

4.) Expected Outcome: My expectation was that upon clicking the filter buttons, the URL would change to reflect the selected filter, mimicking page navigation. Concurrently, the relevant filtered content would be fetched and displayed dynamically.

However, I've encountered challenges. While the URL updates as expected, fetching and displaying new content without refreshing the page has been problematic. I am currently looking into how Alpine.js might help in this regard, particularly in seamlessly updating the DOM with the new content.

I would greatly appreciate any insights, suggestions, or advice, especially from those who have experience with integrating history API methods and Alpine.js in a similar context.

Thanks a lot.

3
  • How often is content expected to be updated? Ajax may not be the answer you're looking for depending on your use case. A websocket might be far more interesting. You'd be able to update content even without the client needing to request it. Commented Nov 11, 2023 at 18:00
  • Hi @icecub, thanks a lot for your input. It's very seldom that the content is updated. Commented Nov 12, 2023 at 14:38
  • In that case using a websocket would cause too much overhead and Ajax is probably the better solution. Personally I'd recommend using jQuery for the Ajax part as it's easier than writing one in plain Javascript. But which ever you choose, all you really need to do is remove the window.location.href = filterUrl; from your button event handler and replace it with an Ajax call to your server and a handler for the response. The accepted answer here shows a small example: stackoverflow.com/questions/50776445/… Commented Nov 13, 2023 at 9:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.