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.
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.
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
Related
I want to check the class of the html (there are posts and every category got a own class for background color) and then set the background.
I wanted to to it with jQuery but it doesn't work because the first one is true so all get the same background.
My php code:
<div class="grid" >
<?php
$args = array( 'post_type' => 'post' );
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post() ; ?>
<div class="post grid-item <?php foreach((get_the_category()) as $category) { echo $category->cat_name; } ?>" style='background: url("<?php if (has_post_thumbnail()) { the_post_thumbnail_url(); } ?>"); background-color:<?php ?>' >
<h1><?php the_title(); ?></h1>
</div>
<?php endwhile;
wp_reset_query();
?>
</div>
my jQuery code that doesn't work
//post background
var back_engagement = jQuery('.grid div').hasClass('engagement');
var back_unternehmen = jQuery('.grid div').hasClass('unternehmen');
var back_forum = jQuery('.grid div').hasClass('forum');
if (back_engagement){
jQuery('.grid-item').css({"backgroundColor": "#959595"});
}
else if (back_unternehmen) {
jQuery('.grid-item').css({"backgroundColor": "#96A306"});
}
else if (back_forum) {
jQuery('.grid-item').css({"backgroundColor": "#215270"});
}
For me it doesn't mater if the solution is with php or jQuery
You can set the CSS property based on simple selector.
jQuery('.grid div.engagement').css({"backgroundColor": "#959595"});
jQuery('.grid div.unternehmen').css({"backgroundColor": "#96A306"});
jQuery('.grid div.forum').css({"backgroundColor": "#215270"});
However I would recommend you to set them using classes in CSS
.engagement{ background-color: #959595;}
What I'm trying to do is the following.
I have a link on my wordpress page that opens a fancybox window and show the content. No header/footer or anything just the content with a thumbnail.
But, and here is my problem, I also would like visitors to be able to visit that page like normal. But now with the header/navigation/footer and all the stuff you would normally see on a webpage.
I tried using media queries (fancybox window is 900x700) but that didn't work. I tried some javascript:
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.single-incl-opt-out').hide();
} else {
$('.single-incl-opt-out').show();
}
});
Still not luck!
Does anyone know what I can do to get this to work?
Update:
Some code examples.
How I load my fancybox content:
<?php echo get_the_term_list_inclusief( $post->ID, 'inclusief', '<p class="extra-text"><i class="fa fa-check"></i> ', '<br><i class="fa fa-check"></i> ', '</p>'); ?>
Some CSS that doesn't work:
#media only screen and (max-width:85em) and (min-width:50em) {
.fancybox-inner .single-incl-opt-out {display: none;}
}
The CSS works when I change my main window size but not like I want it in the fancybox window.
Here is the function to execute the fancybox:
function get_the_term_list_inclusief( $id, $taxonomy, $before = '', $sep = '', $after = '') {
$args_incl = array('order' => 'ASC');
$terms = wp_get_object_terms( $id, $taxonomy, $args_incl );
if ( is_wp_error( $terms ) )
return $terms;
if ( empty( $terms ) )
return false;
$links = array();
usort($terms, function($a, $b) {
return strcmp($a->name, $b->name);
});
foreach ( $terms as $term ) {
$link = get_term_link( $term, $taxonomy, $args_incl );
if ( is_wp_error( $link ) ) {
return $link;
}
$links[] = '<a class="fancybox-incl fancybox.ajax" title="inclusief" href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}
Code for the single-[post-type].php:
<?php get_header(); ?>
<?php the_post(); ?>
<script>
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.single-incl-opt-out').hide();
} else {
$('.single-incl-opt-out').show();
}
});
</script>
<section id="inclusief" style="margin-top:15px;">
<div class="col-sm-5 mobile">
<h1 class="extra-title"><?php the_title(); ?></h1>
<div class="tabcontent" id="tab-<?php the_ID(); ?>">
<p><?php the_content(); ?></p>
</div>
</div>
<div class="col-sm-1"></div>
<div class="col-sm-6 no-padding">
<div class="incl">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
</div>
</div>
</section>
Your current approach to hiding the content based on media queries and window size is not very mobile friendly and it appears that FancyBox already supports this since it's using jQuery's ajax method. More info on that here: http://www.w3schools.com/jquery/jquery_ajax_load.asp
Update your PHP function that loads the FancyBox to include the id of the div you want to load inside of it:
$links[] = '<a class="fancybox-incl fancybox.ajax" title="inclusief" href="' . esc_url( $link ) . '#inclusief" rel="tag">' . $term->name . '</a>';
A similar question/answer can be found here: Jquery FancyBox target specific DIV ID?
I recently download this Slideshow with jmpress.js for a website. I'm using PHP and a database in MYSQL. I used a recordset in Dreamweaver to get the data from database to the site. Then I tried to create a Repeat Region to show the latests posts in the slider.
Headings, images and text are working fine. The problem is on the href (links), which are not changed and remain the same (the ID of the latest post) for all records.
In the head I have these files:
SlideshowJmpress/css/style.css
http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
SlideshowJmpress/js/jmpress.min.js
SlideshowJmpress/js/jquery.jmslideshow.js
SlideshowJmpress/js/modernizr.custom.48780.js
Here is the HTML Code:
<section id="jms-slideshow" class="jms-slideshow">
<?php do { ?>
<div class="step" data-color="color-1">
<div class="jms-content">
<h3><?php echo $row_slider['packageTitle']; ?></h3>
<p><?php echo $row_slider['packageDescription']; ?></p>
<a class="jms-link" href="article.php?ID=<?php echo $row_slider['ID']; ?>">Read more</a>
</div>
<img src="<?php echo $row_slider['packageGraphic']; ?>" width="300px;" height="300px;" />
</div>
<?php } while ($row_slider = mysql_fetch_assoc($slider)); ?>
</section>
<script type="text/javascript">
$(function() {
$( '#jms-slideshow' ).jmslideshow({
});
});
</script>
Here is the php code for the recordset:
$maxRows_slider = 4;
$pageNum_slider = 0;
if (isset($_GET['pageNum_slider'])) {
$pageNum_slider = $_GET['pageNum_slider'];
}
$startRow_slider = $pageNum_slider * $maxRows_slider;
mysql_select_db($database_nipvlach, $nipvlach);
$query_slider = "SELECT * FROM pages ORDER BY `date` DESC";
$query_limit_slider = sprintf("%s LIMIT %d, %d", $query_slider, $startRow_slider, $maxRows_slider);
$slider = mysql_query($query_limit_slider, $nipvlach) or die(mysql_error());
$row_slider = mysql_fetch_assoc($slider);
if (isset($_GET['totalRows_slider'])) {
$totalRows_slider = $_GET['totalRows_slider'];
} else {
$all_slider = mysql_query($query_slider);
$totalRows_slider = mysql_num_rows($all_slider);
}
$totalPages_slider = ceil($totalRows_slider/$maxRows_slider)-0;
Error is either in IDs in your DB or in the slideshow script i think.
Look at source of your page. Are the links right ?
I think that the problem is in the script or in the jmpress.min.js
When I changed slider, everything worked fine!
I tried to implement this mode here http://wordpressthemescollection.com/ajax-wordpress-post-popup-with-simplemodal-and-jquery-488.html but nothing seems to work.
This is what I do.
1 / Include in header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php bloginfo("template_url"); ?>/js/jquery.simplemodal.js"></script>`
The links are goods cause I checked them both.
2 / Include in header this script
<script>
jQuery(document).ready(function() {
jQuery('a.postpopup').live('click', function(){
var id = jQuery(this).attr('rel');
jQuery('<div id="ajax-popup"></div>').hide().appendTo('body').load('<?php bloginfo('url')?>/ajax/?id='+id).modal({
opacity:90,
position: ["0%"],
overlayClose:true
});
return false;
});
});
</script>
3 / Make a custom template with this code
<?php
/*
Template Name: Ajax
*/
?>
<?php
$post = get_post($_GET['id']);
?>
<?php if ($post) : ?>
<?php setup_postdata($post); ?>
<div class="whatever">
<h2 class="entry-title"><?php the_title() ?></h2>
<div class="entry-content">
<?php the_content(); ?>
</div>
</div>
<?php endif; ?>
And after that made a page named Ajax and assign the template Ajax.
4 / Implement a link
this link
If i click on the link nothing happens.
What did I do wrong cause I did not have a clue about it?
Thanks.
jQuery .load() is ajax and so you need to do any subsequent things in a callback like this:
var $ajax-div = jQuery('<div id="ajax-popup"></div>').hide().appendTo('body');
var url = '<?php bloginfo('url')?>/ajax/?id=' + id;
$ajax-div.load(url), function() {
// the callback
jQuery('#ajax-popup').modal({
opacity: 90,
position: ["0%"],
overlayClose:true
});
});
when you create an new post or page content on wordpress admin, select the "Ajax" template for your page
I have a news (blog) page where there are only ever three posts shown at a time (this is the page, how far I have now: http://thewhiteoak.fluroltd.com/our-news/). When a user clicks on a post the main header image at the top of the page will reflect the post thumbnail but a larger version (at the top of the page).
I don't want the post to go through to their own page i.e. single.php as there is no need for it. Can this be done from the generic blog page that displays the three posts? The code below is what I have already which links to a larger image but not in place of the news page.
Can anyone shed some light on this situation please. As I'm getting an Uncaught ReferenceError: img_paths is not defined... But I can't seem to get past this.
This is the import for the mooTools scripts:
<?php if (is_page_template('page-ournews.php')) { ?>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/moo_12.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/moo_12_more.js"></script>
<?php } ?>
The Javascript which will find the link and make it replace the current header image for the post thumbnail.
<script>
window.addEvent('domready', function() {
var images = [];
var loadingimages = [];
var loadingimg_path = ['images/loading-bar-black.gif'];
loadingimg_path.each(function(im) {
loadingimages[im] = new Element('img', {
'src': im,
'styles': {
'visibility': 'visible',
'opacity': '0',
'width': '961px',
'height': '382px',
'border': 'none'
}
});
});
<?php $description = get_post_meta($post->ID, "news-image-thumb", $single = true);
if($description !== '') {
//echo $description;
$pattern = '/href=(?<first>[\'|"])(?<href>[^\1]*?)(?P=first)/i';
preg_match_all($pattern, $description, $matches);
$descr = "'".implode("','", $matches['href'])."'";
?>
var img_paths = [<?php echo $descr; ?>];
<?php
}
?>
var loader = new Asset.images(img_paths, {
onProgress: function(counter,index) {
loadingimages[ loadingimg_path[0] ].set('opacity','0').inject($('frame')).fade(1);
},
onComplete: function() {
//fill our img array
img_paths.each(function(im) {
images[im] = new Element('img', {
'src': im,
'styles': {
'visibility': 'hidden',
'width': '961px',
'height': '382px',
'opacity': '0',
'border': 'none'
}
});
});
//assign click events
$$('#sidenav-content a').addEvent('click', function(e) {
e.stop();
$('frame').empty();
images[this.rel].set('opacity','0').inject($('frame')).fade(1);
});
//show first img in frame
$('frame').empty();
//loadingimages[ loadingimg_path[0] ].set('opacity','0').inject($('frame')).fade(1);
images[ img_paths[0] ].set('opacity','0').inject($('frame')).fade(1);
}
});
});
</script>
The code that displays the posts:
<div id="frame" >
<?php $description = get_post_meta($post->ID, "news-image-large", $single = true);
if($description !== '') {
echo str_replace('<img ','<img width="961" height="382" id="laptopimage" ',$description);
}?>
</div>
<div class="post post-page" id="post-<?php the_ID(); ?>">
<div class="post-content our-news">
<?php the_content(); ?>
<ul id="news">
<?php $page = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("category_name=Our News&showposts=3&paged=$page"); while ( have_posts() ) : the_post(); $loopcounter++; ?>
<li id="postNews" class="post-<?php the_ID(); ?>">
<div class="box">
<?php
<?php if($feature_image_position == 'above'): ?>
<?php if($enable_feature_image == 'yes' && has_post_thumbnail()): ?>
<!--<?php echo theme_TIM_Thumb(317, $feature_image_height); ?>-->
<div id="sidecol">
<div id="sidenav">
<div id="sidenav-content">
<?php if((get_post_meta($post->ID, "news-image-thumb", true))) { ?>
<?php echo get_post_meta($post->ID, "news-image-thumb", true); ?>
<?php } ?>
<br/>
</div><!--sideanv-content-->
</div><!--sideanv-->
</div><!--sidecol-->
<?php endif; ?>
<?php endif; ?>
If I had to guess, this seems like a problem with the interaction between jQuery (which your site appears to be using already) and mooTools (which you added, if I understand correctly). You can start here: Google: mootools noconflict