Drupal/Jquery: hide parent div if child is empty - javascript

I am having difficulty working this out. What I wish to achieve is when works-left and works-right are empty (keeping in mind it functions using drupal pre-processed code) the parent div (latest-works-container) will disappear.
I was wondering if there were somesort of solution to the problem. The thing that came to me was editing the template.php code that is found in bartik, or some other possible solution?
function hybrid_preprocess_html(&$variables) {
if (!empty($variables['page']['featured'])) {
$variables['classes_array'][] = 'featured';
}
if (!empty($variables['page']['services_first'])
|| !empty($variables['page']['services_second'])
|| !empty($variables['page']['services_third'])
|| !empty($variables['page']['services_fourth'])) {
$variables['classes_array'][] = 'services';
}
<div id="latest-works-container"><!--latest-works-container-->
<div id="latest-works"><!--latest-works-->
<div class="works-left">
<?php print render($page['portfolio_works_first']); ?>
</div>
<div class="works-right">
<?php print render($page['portfolio_works_second']); ?>
</div>
<div class="works-left">
<?php print render($page['portfolio_works_third']); ?>
</div>
<div class="works-right">
<?php print render($page['portfolio_works_fourth']); ?>
</div>
</div><!--/latest-works-->
</div><!--/latest-works-container-->

Your element content comes from PHP, so you have no need to remove div using jQuery.
Instead, you should edit your view file. So for example you have you render() method, which gives your the content of div.
$contentBlockFirstLeft = render($page['portfolio_works_first']);
$contentBlockSecondLeft = render($page['portfolio_works_third']);
$contentBlockFirstRight = render($page['portfolio_works_second']);
$contentBlockSecondRight = render($page['portfolio_works_fourth']);
$isLeftBlockEmpty = empty($contentBlockFirstLeft) && empty($contentBlockSecondLeft);
$isRightBlockEmpty = empty($contentBlockFirstRight) && empty($contentBlockSecondRight);
$showAllBlocks = true;
if ($isLeftBlockEmpty && $isRightBlockEmpty) {
$showAllBlocks = false;
}
So you already know all needed information to output your elemnt, so for example you will have next view. Please feel free to change variable names according to business logic needed, those are just dummy names.
<?php if ($showAllBlocks): ?>
<div id="latest-works-container"><!--latest-works-container-->
<div id="latest-works"><!--latest-works-->
<div class="works-left">
<?php echo $contentBlockFirstLeft; ?>
</div>
<div class="works-right">
<?php echo $contentBlockFirstRight; ?>
</div>
<div class="works-left">
<?php echo $contentBlockSecondLeft; ?>
</div>
<div class="works-right">
<?php echo $contentBlockSecondRight; ?>
</div>
</div><!--/latest-works-->
</div><!--/latest-works-container-->
<?php endif; ?>

Related

Pass single PHP value from ACF Repeater Field

I have a page for team members of a company. The team members are rendered with an ACF repeater that has fields for Name, Job Title, and Biography. On the page I would like to render just their Name, and Job Title. If you were to click on a team member, that would open a modal that would render that team members biography.
I have this working, but my approach adds the Biography field to the DOM for each team member, hides it, and passes it into the modal on click. I am wondering if it is possible to pass the Biography field into the modal without having to render the text in the DOM initially and hiding it?
Below is my current code:
<!-- acf repeater -->
<?php if( have_rows('team_member') ): ?>
<?php while( have_rows('team_member') ): the_row();
$name = get_sub_field('name');
$job_title = get_sub_field('job_title');
$biography = get_sub_field('biography');
?>
<div class="team-member">
<div>
<?php echo $name ?>
</div>
<div>
<?php echo $job_title ?>
</div>
<div class="biography" style="display: none;">
<?php echo $biography ?>
</div>
</div>
<?php endwhile; ?>
<!-- modal -->
<div class="modal">
modal
<div class="modal-biography">
</div>
</div>
<?php endif; ?>
<!-- javascript -->
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).find('.biography').text();
$('.modal-biography').text(modalBiography);
})
});
If you don't need to display the bio div, I'd suggest just putting it into a data-bio attribute:
<div class="team-member" data-bio="<?php echo $biography; ?>">
<div><?php echo $name; ?></div>
<div><?php echo $job_title; ?></div>
</div>
then tweak js a bit to pull this data-bio instead:
jQuery(function($) {
$('.team-member').on('click', function() {
var modalBiography = $(this).data('bio');
$('.modal-biography').text(modalBiography);
})
});

Window on load function is not firing until i refresh page manually?

I'm showing a loading bar before the content loads successfully. And after load I am displaying the content by jQuery but when i visit the page first time the loader is showing forever and the on load event isn't firing. It fires when i manually refresh the page. What's wrong with my code?
Event call code:
$(window).on('load', function(){
$("#slider-pre-loader").fadeOut("slow");
$("#video-blog-slider").fadeIn();
});
Dynamic HTML:
<div id="slider-pre-loader"></div>
<div id="video-blog-slider" style="display: none">
<div class="blog-category-items blog-page" id="blogIndex">
<div class="container">
<?php
$hpos = 0;
foreach ($categories as $category):
$categoryhref = fakeUrl::genSlugFromText($category['name']);
$listVideos = $category['videos'];
if (in_array($category['name'], $categoryDisplay)) :
?>
<div class="blog-groups">
<div class="group-heading">
<h3>
Test title
</h3>
</div>
<?php if ($category['desc'] != '') :?>
<p class="group-desc"><?php echo $category['desc'];?></p>
<?php endif;?>
<?php
$slideClass = '';
if (!$detect->isMobile() && !$detect->isTablet() ) {
$slideClass = 'blog-slider';
}
?>
<div class="<?php echo $slideClass;?> owl-lg-dot mb-none owl-theme owl-loaded" id="videoList">
<?php
$v = 0;
foreach ($listVideos as $video) :
$v++;
$itemClass = '';
if (($detect->isMobile() || $detect->isTablet()) && $v > 5) {
$itemClass = 'item-disable';
}
$videoSlug = fakeUrl::genSlugFromText($video['title']);
?>
<div class="blog-item <?php echo $itemClass;?>">
<div class="blog-image">
<a href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="caption">
<a class="blog-list-video-title" href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="blog-metas">
<small class="blog-views"><?php echo number_format($video['views']); ?> views</small>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<?php
endif;
endforeach;
?>
</div>
</div>
</div>
jQuery placed before event call:
<script src="//code.jquery.com/jquery-1.11.3.min.js" async></script>
Don't place async attribute on your script tags unless you really need your script file to be loaded asynchronously. Right now, your 'jQuery' code is being loaded asynchronously, i.e. jQuery is most probably not loaded when you are trying to attach your event.
The only explanation for it working the second time upon manual refresh is that the browser is 'synchronously' loading the cached resource. Different browsers do this differently, so you can expect inconsistent behaviour there.
Just remove the async attribute, and you should see your event firing every time.
The $(window) selector is for selecting the viewport whereas the $(document) selector is for the entire document (that is, what's inside the <html> tag).
Try using the following:
$(document).on('load', function(){
$("#slider-pre-loader").fadeOut("slow");
$("#video-blog-slider").fadeIn();
});
I hope this working with you, I have created example you will be woking with document.ready it means JQuery see and focus on all elements in your web page, here is fiddle
Simple for test
<div id="slider-pre-loader">no</div>
<div id="video-blog-slider" style="display: none">
hi
</div>
OR your code
<div id="slider-pre-loader">no</div>
<div id="video-blog-slider" style="display: none">
<div class="blog-category-items blog-page" id="blogIndex">
<div class="container">
<?php
$hpos = 0;
foreach ($categories as $category):
$categoryhref = fakeUrl::genSlugFromText($category['name']);
$listVideos = $category['videos'];
if (in_array($category['name'], $categoryDisplay)) :
?>
<div class="blog-groups">
<div class="group-heading">
<h3>
Test title
</h3>
</div>
<?php if ($category['desc'] != '') :?>
<p class="group-desc"><?php echo $category['desc'];?></p>
<?php endif;?>
<?php
$slideClass = '';
if (!$detect->isMobile() && !$detect->isTablet() ) {
$slideClass = 'blog-slider';
}
?>
<div class="<?php echo $slideClass;?> owl-lg-dot mb-none owl-theme owl-loaded" id="videoList">
<?php
$v = 0;
foreach ($listVideos as $video) :
$v++;
$itemClass = '';
if (($detect->isMobile() || $detect->isTablet()) && $v > 5) {
$itemClass = 'item-disable';
}
$videoSlug = fakeUrl::genSlugFromText($video['title']);
?>
<div class="blog-item <?php echo $itemClass;?>">
<div class="blog-image">
<a href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="caption">
<a class="blog-list-video-title" href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="blog-metas">
<small class="blog-views"><?php echo number_format($video['views']); ?> views</small>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<?php
endif;
endforeach;
?>
</div>
</div>
</div>
Javascript:
$(document).ready(function() {
$("#slider-pre-loader").fadeOut('slow');
$("#video-blog-slider").fadeIn('slow');
});

Wordpress - Show random post with JS, not PHP

I have this page containing recent posts at the bottom. I have set it to randomly show me three posts from the same category as the current post. Heres the loop:
<!-- Related Posts =========================================== -->
<div class="relared-posts-heading">
<h2>SIMILAR INSIGHTS</h2>
</div>
<div class="container blog-card-container">
<div class="card-columns">
<?php
// the query
$the_query = new WP_Query( array(
'orderby' => 'rand',
'cat' => '-14',
'posts_per_page' => 3,
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!-- Conditional a Link =========================================== -->
<?php
if(get_field('quote') == ''){
$yourTag = "<a href='".get_the_permalink()."'>" ;
} else {
$yourTag = "";
}
?>
<div> <?php echo $yourTag; ?> </div>
<div class="card">
<a href="<?php the_permalink(); ?>">
<div class="blog-thumb-container-2">
<?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
</div>
</a>
<div class="blog-meta-container-2">
<p class="blog-cat-label"><?php the_category(', '); ?></p>
<h2 class="blog-card-title"><?php the_title(); ?></h2>
<p class="card-text"><?php the_excerpt(__('(moreā€¦)')); ?></p>
<p><strong><?php the_author(); ?></strong> | <?php echo get_the_date(); ?> </p>
</div>
</div>
</a>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No News'); ?></p>
<?php endif; ?>
</div>
</div>
This works fine currently.
The trouble is, when finished, the site will be behind a clients custom cache and he tells me that PHP randomisers wont work as it will just show the cached version. He suggested I do any randomising using Javascript!
So firstly - is this possible? Secondly, How would I go about targeting this is javascript!? Thanks for looking!!
Unfortunately you won't be able to randomize a post in this way for the caching reason.
What you can do instead is use an Ajax call to dynamically fetch and insert a random post...
$.get('/wp-content/themes/SomeTheme/random.php?v=' + Math.floor(Date.now() / 1000))
.done(function(resp) {
$('.random-post').html(resp);
})
.fail(function(xhr) {
// handle error (xhr object contains the response)
});
And then create a separate random.php file in your theme and put the code to randomly return a single post in there. Note, that you don't need to put the whole layout around the post (don't include header.php etc). That's because this exact HTML fragment will be sent to the frontend and inserted dynamically.
The ?v= parameter is required for cache busting so that it fetches a new post each time.
Try wrapping the entire funtionality as a shortcode.

PDO fetch then targeted object?

I currently have a page where I'm connecting to db via PDO, db, prepare.
Selecting SQL_CALC_FOUND_ROWS in order to have pagination with the results.
All of that is good. However, each return is to have a text popup when clicked. Thats where I want to target a particular field of defined row.
Code I have is as follows :
$db = new PDO('mysql:dbname=###;host=###','###','###');
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ?(int)$_GET['per-page'] : 8;
//Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
//Query
$articles = $db->prepare("
SELECT SQL_CALC_FOUND_ROWS id, comment_caption, comment_sub_caption,comment_title, comment_main, comment_name,
comment_date, comment_url
FROM TABLE_NAME
LIMIT {$start}, {$perPage}
");
$articles->execute();
$articles = $articles->fetchAll(PDO::FETCH_ASSOC);
// Pages
$total = $db->query("SELECT FOUND_ROWS() as total")->fetch()['total'];
$pages = ceil($total / $perPage);
//Pagination div
<div class="pagination">
<?php for($x = 1; $x <= $pages; $x++): ?>
<a href="?page=<?php echo $x; ?>&per-page=<?php echo $perPage; ?> "<?php if($page === $x){ echo 'class="selected"'; }?>><?php echo $x ?></a>
<?php endfor; ?>
</div>
// Here is the container for the foreach
<div id="container">
<?php
foreach($articles as $article): ?>
<div class="item small">
<div class="module">
<div class="article">
<div class="item-inner">
<a href="<?php echo $article['comment_url']; ?>">
<div class="project-title">
<div class="mid">
<h2><?php echo $article['comment_caption']; ?></h2>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
// This is the popup that I want to associate with each return
<div id="test-popup" class="white-popup mfp-hide">
<blockquote><?php echo $article['comment_main'];
?></blockquote>
<p><i><?php echo $article['comment_name']; ?> - <?php echo $article['comment_date']; ?></i></p>
</div>
In the popup, I want to echo the 'comments_main, comments_name & comments_date' field of the particular instance that is clicked. Here currently, it just echos the first row.
I'm not sure what the best way to go about it is... ?
Any help would be greatly appreciated.
This is not really a php-mysql related question, but rather a javascript-html-css related one.
You have 2 options:
You output the comments_main, comments_name & comments_date fields to all listed items in a way they are not visible to the users first in the browser. Typically, you could use the anchor element's title property, or html5's data- properties, or even a list of invisible divs. Whenever the user clicks a link, you use javascript to fetch these data for the given comment from your list on the client side (if they are not stored in a list of divs already) and make it appear.
You do not output these data to the client, but upon clicking you use an ajax call to retrieve these data from the server via another php page.
For both approach there are lots of tutorials out there with designed boxes (tooltips) and copy-paste javascript, html, and css code.

Trying to display data shown depending on what users click

Have a look here:
http://test.neworgan.org/100/
Scroll down to the community section.
What I'm trying to achieve is to get the data for new organizers, (e.g.: number of friends / amount donated) to show once users click on their thumbnails. right now each user has his or her own unique data stored externally.
Once the users click the thumbnail, 'inline1' appears with the content.
As of now, I'm only able to get the data from the last user to show regardless of whichever user's thumbnails I'm clicking on. I just need a bit of help as to how to change the content depending on which thumbnail users click. So I was wondering if I could have some help here?
Here's that part of the code that matters:
<div class="top-fundraisers-wrapper">
<div class="subsection top-fundraisers">
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline1">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
</div>
</div>
</div>
<div id="inline1">
<div class="top-fundraiser-image2">
<img src="<?php
if($fundraiser['member_pic_large']) { print htmlentities($fundraiser['member_pic_large']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
<span class="member-name"><?php print htmlentities($fundraiser['member_name']); ?></span>
<span class="friend-count"><?php print number_format($fundraiser['num_donors']) . (($fundraiser['num_donors'] == 1) ? ' Friend' : ' Friends'); ?></span>
<span class="fundraisers-text"> Donated: </span><span class="fundraisers-gold"> $<?php print number_format($fundraiser['total_raised']); ?></span>
</div>
Best way is to use Ajax. Something like this
$("#button").click( function() {
$.ajax({
url: 'file.php',
method: 'post',
data: { id: $(this).val() },
error: function() {
alert('error while requesting...');
}, success: function(data) {
alert( data ); /** received data - best to use son **/
}
});
});
Next parse json var json = $.parseJSON(data);
or ... use dataJson option.
Next Your data should be inserted using class or id to specific location.
Create another loop for content
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline<?php echo $i; ?>">
// ... content
<?php $i++;
endforeach;
endif; ?>
And another loop
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<div id="inline<?php echo $i; ?>">
// inline content here
</div>
<?php $i++;
endforeach;
endif; ?>
Hope your JavaScript function to open fancybox works fine via calling class. So by following code you do not need to play with Javascript code.
Building anchors tags:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<a title="" class="fancybox" href="#inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</a>
<?php
} //end of foreach
} // end of if condition
?>
Building Popup HTML DOMs:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<div id="inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</div>
<?php
} //end of foreach
} // end of if condition
?>
You cannot perform this because PHP runs server-side and JavaScript runs in the browser.
To perform this you can use AJAX to get the div as required by user.
...or store the data client-side and change the content of #inline1 based on which item was clicked

Categories