Javascript cannot see HTML from Wp_query
-
Hi
I’m hoping you can help me understand a problem I’m experiencing. I’m working on a page that shows posts categorised as 12 or 13 within a feed. There are two buttons at the top of the feed which, when clicked, hide some of the content – at least it should!
To do this I have:
- JS – written a piece of js that, upon clicking one of the buttons adds a class (either .turnedon or .turnedoff) to items with a specified class.
//Extra javascript v1.1 should hide/unhide resultsblob classed as 13 jQuery(document).ready(function() { console.log("bla"); jQuery("#everything").click(function(){ jQuery('[data-categories="13 "]').addClass("turnedon"); jQuery('[data-categories="13 "]').removeClass("turnedoff"); jQuery("#everything").addClass("barcontaineron"); jQuery("#reading").removeClass("barcontaineron"); jQuery("#everything").removeClass("barcontaineroff"); jQuery("#reading").addClass("barcontaineroff"); }); jQuery("#reading").click(function(){ jQuery('[data-categories="13 "]').addClass("turnedoff"); jQuery('[data-categories="13 "]').removeClass("turnedon"); jQuery("#reading").addClass("barcontaineron"); jQuery("#everything").removeClass("barcontaineron"); jQuery("#reading").removeClass("barcontaineroff"); jQuery("#everything").addClass("barcontaineroff"); }); });
- functions.php – I have enqueued this script within my custom functions php file
function SHdemo_scripts() { wp_enqueue_script('extra js', get_stylesheet_directory_uri() . '/js/extra.js'); } add_action('wp_enqueue_scripts', 'SHdemo_scripts'); ?>
- Wp_query – I have added the posts to the page via a new WP query and used the category id to assign a class to the containing divs
<?php //SH results feed ordered by date $resultsPosts = new WP_Query('cat=12,13&posts_per_page=9'); if ($resultsPosts->have_posts()) : while ($resultsPosts->have_posts()) : $resultsPosts->the_post(); ?> <div class="resultsblob" data-categories="<?php foreach((get_the_category()) as $category) { echo $category->cat_ID . ' '; } ?>"> <h2><?php the_title(); ?></h2> <?php the_content(); ?> </div> <?php endwhile; else: //fallback no content message here endif; //This stops wordpress from killing life wp_reset_postdata(); ?>
So my wpquery dumps all the content on my page assigning each item a class based on its ID and then my javascript adds the class .turnedon or .turnedoff to these items depening on which button is pressed.
The problem I’m experiencing is that while the JS has no problem interacting with the standard HTML on the page, it just cannot see the HTML supplied via the WPquery. Is this something to do with the order that the js is called compared to the wp_query being run?
Hope you can help.
Many thanks
Dune - JS – written a piece of js that, upon clicking one of the buttons adds a class (either .turnedon or .turnedoff) to items with a specified class.
- The topic ‘Javascript cannot see HTML from Wp_query’ is closed to new replies.