iceiceicy
iceiceicy

Reputation: 734

Load 2 content into 2 div respectively jquery

Is it possible to simplify this call?

$('.tag-widget a').click(event => {
    event.preventDefault()
    $('.products-grid').load(`${event.target.href} .products-grid`)
    $('.pagination-cubic').load(`${event.target.href} .pagination-cubic`)
})

Basically, when I click the link under the .tag-widget, I want the content from .pagination-cubic & .products-grid to load into its respective div.

The above codes work for me, but it's making 2 calls which affected the loading time. Can I combine them into 1?

I tried this below codes, but what happen is the .products-grid loads into both the .pagination-cubic & .products-grid.

jQuery(document).ready(function ($) {
    $('.tag-widget a').click(event => {
        event.preventDefault()
        $('.products-grid, .pagination-cubic').load(`${event.target.href} .products-grid, .pagination-cubic`)
    })
});

P/s : Searching through the forum, I only found the way to insert 2 contents into 1 div only.

Upvotes: 0

Views: 46

Answers (1)

31piy
31piy

Reputation: 23859

The docs for .load() suggest that

It is roughly equivalent to $.get(url, data, success) ...

So, you should be able to do something like this:

$.get(event.target.href, function(resp) {
  var resp = $(resp);

  $('.products-grid').html(resp.find('.products-grid').html());

  if (resp.find('.pagination-cubic').length > 0) {
    $('.pagination-cubic').html(resp.find('.pagination-cubic').html());
  } else {
    $('.pagination-cubic').html('');
  }
});

This will fetch the contents once and then set the HTML content of appropriate selectors.

Upvotes: 1

Related Questions