Home  >  Q&A  >  body text

Script not running properly after Ajax call

I'm building my own portfolio website on WordPress and writing almost the entire code without plugins. The website's home page comes with a dynamic "Custom Post Type" grid and I have implemented an Ajax filter based on the post taxonomy/category and reordered the posts based on the filter. The script is run on script.js:

(function ($) {

  $(document).ready(function () {
    $(document).on('click', '.js-filter-item', function (e) {
      e.preventDefault();
      $('.js-filter-item').removeClass('active');
      $('.js-filter').addClass('fade');
      $(this).addClass('active');
      setTimeout(function () {
        $('.js-filter').removeClass('fade');
      }, 500);
      var category = $(this).data('category');
      $.ajax({
        url: wpAjax.ajaxUrl,
        data: { action: 'filter', category: category },
        type: 'POST',
        success: function (result) {
          // $('.js-filter').html(result);
          setTimeout(function () {
            $('.js-filter').html(result);
          }, 200);
        },
        error: function (result) {
          console.warn(result);
        }
      })
    });
  });

I also implemented a custom tooltip that follows the cursor and displays the post title on hover, as shown below. This is the php file that runs between the home page tags:

var follower = $('.cursor-follower');
var posX = 0,
  posY = 0;
var mouseX = 0,
  mouseY = 0;
 
$('body').on('mousemove', function (e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
  posX += (mouseX - posX) / 2;
            posY += (mouseY - posY) / 2;
  
  $('.cursor-follower').css(
    'top', (posY - 20) + 'px'
);
$('.cursor-follower').css(
    'left', (posX + 50) + 'px'
);
});

$('.animated-cursor').on('mouseenter', function () {
 console.log('olaaaaa');
  var dataTitle = $(this).attr('data-cursor-title');
  // var dataTags = $(this).attr('data-cursor-tags');
  follower.html(dataTitle + '<br>');
  follower.addClass('active');
});
$('.animated-cursor').on('mouseleave', function () {
  follower.removeClass('active');
});

And the query for the posts grid (the "animated-cursor" class and data-cursor-title are relevant properties):

if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();  ?>
    <div class="reveal item animated-cursor" data-cursor-title="<?php the_title(); ?>">
        <a href="<?php the_permalink(); ?>">
        <?php $pagina = get_page_by_title('<?php the_title(); ?>') ?>
          <img src="<?php the_field('imagem_capa', $pagina); ?>" alt="">
          <div class="post-info">
          <div>
            <h3><?php echo wp_strip_all_tags(get_the_term_list( $post->ID, 'portfolio_cat', '', ', ', '' )) ?></h3>
            <h2><?php the_title(); ?></h2>
</div>
          </div>
        </a>
      </div>
      <?php
        endwhile; 
      endif; 
      wp_reset_postdata(); 
       die();

Issue: Custom cursor tooltip does not work on element hover after using Ajax filter. Everything works fine as planned after the page loads, but at no time does the Ajax run.

As far as I know (I'm a beginner in php, ajax, js), my script can only access elements that are prepared when the page loads. I'm trying to get the script to work after an Ajax call but can't find a way around it. Does anyone have any suggestions? I thought it wouldn't be complicated.

Thanks!

P粉642919823P粉642919823287 days ago440

reply all(1)I'll reply

  • P粉323050780

    P粉3230507802024-01-30 10:14:25

    The problem is: JavaScript is bound to the existing DOM, which is valid on the first render. But after the ajax call, the new DOM will be appended to the HTML. The new DOM won't have functionality bound, so hover won't work.

    The solution is, don't bind the event to the DOM itself. You can bind event listeners to the parent annotation or the page body For example

    $('body').on('mouseenter', '.animated-cursor', function () {
     console.log('olaaaaa');
      var dataTitle = $(this).attr('data-cursor-title');
      // var dataTags = $(this).attr('data-cursor-tags');
      follower.html(dataTitle + '
    '); follower.addClass('active'); }); $('body').on('mouseleave', '.animated-cursor', function () { follower.removeClass('active'); });

    reply
    0
  • Cancelreply