0

I am trying to load wordpress post in div using ajax but the jQuery inside it wont work after loading the content. For example i have accordian and slider in loaded page, they also dont work. And also the close button for the loaded div not working too.

I checked this post too Jquery event handler not working on dynamic content

But no sucess.

portfolio.php

<div id="fff">

</div>


<h2 class="ow-heading"><?php the_title(); ?></h2>
    <?php the_content(); ?>
<ul class="projectlist clearfix" id="<?php global $post; $post_slug=$post->post_name; echo $post_slug; ?>">
<?php
global $wp_query;
query_posts( array('post_type' => array( 'portfolio' ),'showposts' => 12, 'paged'=>$paged )
);
if (have_posts()) : while (have_posts()) : the_post();
?>
<li class="project">
    <a href="<?php the_permalink(); ?>" data-post="" rel="<?php the_ID(); ?>" class="ajax" data-toggle="modal" data-target="#myModal">
        <?php if ( has_post_thumbnail() ) { ?>
        <?php the_post_thumbnail(); ?>
        <?php } ?> 
        <div class="projectinfo">
            <div class="meta">
                <h4><?php the_title(); ?></h4>
                <h6><em><?php echo get_post_meta($post->ID, "spq_portfolio_tag", true) ?></em></h6>
            </div>
        </div>
    </a>
</li>
<?php endwhile; ?>
<?php else: ?>
<p><?php _e("Sorry, no posts matched your criteria.","arclite"); ?></p>
<?php endif; wp_reset_query(); ?>
</ul>

single-portfolio.php

<?php get_header(); ?>
  <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
  <div class="sparq-main">
    <div class="insparq-main">

      <h1 class="portfolio-single-title"><?php the_title(); ?></h1>
      <?php the_content(); ?>
    </div>
  </div>
<?php endwhile; endif; ?>
<?php get_footer(); ?>

custom.js

jQuery.noConflict();
jQuery(document).ready(function(){



/*----------------------------------------------------*/
/* Sticky Navigation
/*----------------------------------------------------*/ 

jQuery(".bottommenu").sticky({ topSpacing: 0 });

/*----------------------------------------------------*/
/* Slab Text
/*----------------------------------------------------*/  

function slabTextHeadlines() {
jQuery("h1.tagline").slabText({
      "viewportBreakpoint":380
    });
};
jQuery(window).load(function() {
    setTimeout(slabTextHeadlines, 1000);
});

/*----------------------------------------------------*/
/* Parallax
/*----------------------------------------------------*/

jQuery('.sep, .header').each(function(){
   jQuery(this).parallax("100%", 0.3); 
});

/*----------------------------------------------------*/
/* Accordion
/*----------------------------------------------------*/

jQuery('.accordion').each(function(){
      var acc = jQuery(this).attr("rel") * 2;
      jQuery(this).find('.accordion-inner:nth-child(' + acc + ')').show();
       jQuery(this).find('.accordion-inner:nth-child(' + acc + ')').prev().addClass("active");
});

jQuery('.accordion .accordion-title').click(function() {
      if(jQuery(this).next().is(':hidden')) {
          jQuery(this).parent().find('.accordion-title').removeClass('active').next().slideUp(200);
          jQuery(this).toggleClass('active').next().slideDown(200);
      }
      return false;
});

/*----------------------------------------------------*/
/* Custom Scroll
/*----------------------------------------------------*/

jQuery("html").niceScroll({cursorborder:"0px solid #fff",cursorwidth:"10px",scrollspeed:"70"});

/*----------------------------------------------------*/
/* Flex Slider
/*----------------------------------------------------*/

jQuery('.testi').flexslider({
    selector: ".slides > li",
    directionNav: false 
});

/*----------------------------------------------------*/
/* Navigation Scroll to Section
/*----------------------------------------------------*/

  var device = navigator.userAgent.toLowerCase();
  var ios = device.match(/(iphone|ipod|ipad)/);
 //function that returns element's y position

    jQuery("a[href*=#]").on('click', function(e) {
      var scrollTarget = jQuery(this.hash).offset().top;
      if(scrollTarget) 
          e.preventDefault();
        if(parseInt(scrollTarget) !== parseInt(jQuery(window).scrollTop())) {
          var nav2 = jQuery("nav");
        if (ios) nav2.hide();
          jQuery('html,body').animate({scrollTop:scrollTarget}, 1000, "swing", function(evt) {
          if (ios) {
            if(scrollTarget == 0) 
                nav2.css({position:'absolute', top:jQuery("#intro").height()});
            else
                nav2.css({position:'absolute', top:scrollTarget});
            var nav2clone = jQuery("nav")
            nav2clone.show();
          }
      });
    }
    });

    if (ios) {
        jQuery(document).bind('touchmove',function(){
          var intro = jQuery("#intro"), nav2 = jQuery("nav");
          console.log(nav2.position().top);
        if(intro.height() != nav2.position().top)
        {
            nav2.css({position:'fixed', top:'0px'});
            console.log(nav2.position().top);
        }
        else
        {
            nav2.css({position:'relative', top: ''});
        }
      });   
    }

/*----------------------------------------------------*/
/* Fit Video Responsive
/*----------------------------------------------------*/

jQuery(".spq-video").fitVids();
});

Ajax Call

jQuery("a.ajax").on('click', function(e) {
    e.preventDefault();
    var url = jQuery(this).attr("href");
    jQuery.get(url, function(data) {
      jQuery("#fff").show(600).html(data);
      var scrollTarget = jQuery("#fff").offset().top;
          jQuery('html,body').animate({scrollTop:scrollTarget-80}, 1000, "swing");
    });
  });

After the page content load with ajax, all the elements associated with custom.js not working, like slider, accordion etc.. which are on loaded content stopped working.

Community
  • 1
  • 1
Vikas Ghodke
  • 6,602
  • 5
  • 27
  • 38
  • 2
  • @tushargupta posted the code. – Vikas Ghodke Oct 02 '13 at 05:45
  • 3
    More specifically, post HTML only. No PHP. Use 'View Page Source' if you have to. – Joe Simmons Oct 02 '13 at 05:46
  • Even better, a jsFiddle. – Joe Simmons Oct 02 '13 at 05:48
  • `jQuery inside it wont work` what you mean by this? the ajax content has the jQuery that doesnt work or your jQuery does not work on dynamic content? what behavior do you expect from dynamic content? should they be converted to accordions/sliders? – Shaheer Oct 02 '13 at 05:51
  • your close button is not working because it does not use `jQuery.on` (`jQuery("a.pclose").click`) convert it to `jQuery.on` and it will work – Shaheer Oct 02 '13 at 05:52
  • I assume you're using bootstrap? accordion, sliders or any javascript component won't work when loaded via ajax unless you manually initialize them – omma2289 Oct 02 '13 at 06:13
  • Your use of `on` looks correct, but are your functions wrapped in a jQuery "ready" call? Please post the entire page output (in a JSFiddle) so we can see where it might be going wrong. PHP is less useful than a dump of the page source when run. – iCollect.it Ltd Oct 02 '13 at 08:30
  • PHP is not as useful as the source from the running page. That removes the need for the entire backend/configuration. Please add that (preferably to a JSFiddle). – iCollect.it Ltd Oct 02 '13 at 13:29

2 Answers2

2

Your code works as-as if you wrap it in a jQuery "ready".

I mocked up a JSFiddle of your page here:

http://jsfiddle.net/NEest/

jQuery(function () {
    jQuery(document.body).on('click', 'a.ajax', function () {
        var post_url = jQuery(this).attr("href");
        var post_id = jQuery(this).attr("rel");
        alert(post_url + " - " + post_id);
        jQuery("#fff").html('<div class="loading">loading...</div>');
        jQuery("#fff").load(post_url).fadeIn(500);
        return false;
    });

    jQuery("a.pclose").click(function () {
        jQuery("#fff").fadeOut();
    });
});

Please note: JSFiddles do not require the "ready" code as it is a built-in feature (drop-down option on left), but it does not hurt to add it for demonstration purposes.

If you can update the JSFiddle with any remaining issues that will make it easier for everyone to help.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • Thanks for your help, i have updated my question for more clearance, if you can look into it then it would be really helpfull. – Vikas Ghodke Oct 02 '13 at 10:26
  • Happy to help, but PHP is not as useful as the source from the running page. That removes the need for the entire backend/configuration. Please add that (*preferably to a JSFiddle*). – iCollect.it Ltd Oct 02 '13 at 13:26
-2

All jquery plugins read the dom of the document when the page load, so n order to enable the jquery functionality on ajax loaded content you have to re initialize the jquery plugins. then your code will work.
Please check my answer on this post as well

Community
  • 1
  • 1
Shani
  • 142
  • 2
  • 9
  • 2
    This is incorrect. The deferred syntax of `on` connects the events to the document, not the elements, and filters the call *when* they are triggered. That allows events to be called on elements that will exist later. – iCollect.it Ltd Oct 02 '13 at 08:27
  • Thanks for your help, i have updated my question for more clearance, if you can look into it then it would be really helpfull – Vikas Ghodke Oct 02 '13 at 10:26