Unset img src if no url is provided vue.js - javascript

I'm learning vue.js
I'm testing how it works with ajax and the wp rest api, I'm creating a custom panel theme and I want to show the content on the right side of the screen in a scrollable panel and the pages on the left side of . the screen without the possibility to scroll.
I'm able to display the content of the posts and pages, I'm getting also the featured image, and I placed it inside an <img> tag. I need to understand how to tell vue.js that if there isn't any url data to show the featured image, the src of the image element needs to be unset. Is this possible ?
<?php get_header(); ?>
<div class="container-fluid content-wrapper" style="overflow:hidden;height:100vh;">
<div class="row" id="app" style="margin:2em 0 2em 0;">
<!-- Sidebar Top Area -->
<div class="col-sm-12 col-md-4 col-lg-4" id="navPanel" style="padding:2em;">
<?php $links = new WP_Query( array('post_type' => 'page', 'posts_per_page' => -1) ); ?>
<?php if( $links->have_posts() ): while( $links->have_posts() ): $links->the_post(); ?>
<h1 class="home-claim" style="font-size:2em;">
<a class="" href="#" v-on:click.prevent="getContent(<?php echo get_the_ID(); ?>)" ><?php the_title(); ?></a>
</h1>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
<!-- Post/Pages Content -->
<div class="col-sm-12 col-md-8 col-lg-8" id="contentPanel" style="padding:0 0 2em 0;overflow:auto;height:100vh;">
<!-- Image here -->
<img class="img-fluid w-100" v-if="featuredImage" v-bind:src="featuredImage" />
<div class="" id="" v-html="content"></div>
</div>
<!-- Sidebar Bottom Area -->
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
(function($){
$(document).ready(function(){
var app = new Vue({
el: '#app',
data: {
content: null,
featuredImage: null,
},
mounted: function(){
},
methods: {
getContent: function(id){
console.log('method Fired!');
var self = this;
console.log(id);
var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
$.getJSON( url, function(data){
console.log(data);
self.content = data.content.rendered;
self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
//console.log(data._embedded["wp:featuredmedia"][0].source_url);
//console.log(data.content.rendered);
});
}
}
});
}); // doc ready
}(jQuery));
</script>
<?php get_footer(); ?>
I've also noticed that only for a page I have, the wp api will return a 401 code for the featured image.
Any help will be appreciated.

Unset the featuredImage before doing the load:
(function($){
$(document).ready(function(){
var app = new Vue({
methods: {
getContent: function(id){
var self = this;
// unset the image before you are loading.
// this way it will also unset when the loading fails.
self.featuredImage = null;
var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
$.getJSON( url, function(data){
self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
});
}
}
});
});
}(jQuery));

Related

JavaScript modal

I have a WordPress site loading a JS file named script.js, which is loaded always. In that file I have this function:
$(document).ready(function() {
$("button.demo-2").on("click", function (e) {
var options = {
width: "1200px",
height: "100%",
closeCross: true,
escapeKey: true,
beforeOpen: function () {
$("body").addClass("popupOpened")
},
};
e.preventDefault();
$(this).simplePopup({type: "html", htmlSelector: "#myPopup"});
});
});
The HTML code for the page /product/experience:
<button href="#" class="button demo-2">Más info</button>
<div id="myPopup">
<h2><?php _e( 'More information about', 'exp-theme' ); ?></h2>
<h3><?php the_title( ); ?></h3>
<?php
if(ICL_LANGUAGE_CODE == "es"){
echo do_shortcode('[contact-form-7 id="705" title="+Info experiencias"]');
}else{
echo do_shortcode('[contact-form-7 id="40" title="Contacto"]');
}
?>
</div>
If I load that page directly, the modal works correctly. But if I'm in the home and go to /product/experience, the modal is not working until I reload /product/experience.
I don't know which is the better approach. Load the function only in this page? Maybe use another way to do it instead $(document).ready?

Property or method "navlink" is not defined on the instance but referenced during render - Vue.js

I'm having some problem with vue.js
I'm learning how to create components and I'm making some components that I want to use for a wordpress theme. I'm using the REST API to get the contents and pass the response data from axios to the UI managed by vue and vue coponents. I'm getting always this error:
Property or method "navlink" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property
This happen after I've created a new component for the nav menu, I think the code is correct but any help will be appreciated. I have the home.php file that will be used for the homepage as a template using Template Name: on top of the file and inside the header.php file I've removed the old menu and I've placed a vue template. I will do the same for the footer, but how I can fix errors that are caused by widgets or wordpress generated inline scripts? How I can fix my error ?
// this is the code of header.php
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="profile" href="http://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div class="container-fluid p-0" id="theme-vue">
<theme-nav v-for="nav in navData" :navlink="nav.post_title"></theme-nav>
<script type="text/x-template" id="theme-nav">
<nav class="navbar navbar-expand-md fixed-top main-nav">
<button class="navbar-toggler hamburger hamburger--spin" type="button" data-toggle="collapse" data-target="#navbar-content" aria-controls="navbar-content" aria-expand="false" aria-label="<?php _e('Toggle Navigation'); ?>">
<span class="hamburger-box">
<span class="hamburger-inner"></span>
</span>
</button>
<a class="navbar-brand ml-auto" href="#">
<img src="" width="auto" height="75">
</a>
<div class="collapse navbar-collapse navbar-content" id="navbar-content">
<ul class="navbar-nav mx-auto">
<li class="nav-item">
<a class="nav-link top" href="#">{{ navlink }}</a>
</li>
</ul>
</div>
</nav>
</script>
// this is the code of home.php
<?php /* Template Name: Homepage */ ?>
<?php get_header(); ?>
<uptheme-cover v-for="post in postData" :title="post.title.rendered" :src="post._embedded['wp:featuredmedia'][0].source_url"></uptheme-cover>
<script type="text/x-template" id="uptheme-cover">
<div class="row container-cover p-0" style="height:100vh;">
<div class="parallax" :data-parallax-image="src"></div>
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12 p-4">
<h1>{{ title }}</h1>
</div>
</div>
<div class="overlay"></div>
</div>
</script>
<?php //get_footer(); ?>
// this is the footer, it will cause error in vue because of the google map iframe footer widget and wordpress footer scripts
<?php wp_footer(); ?>
<div class="row p-0 footer">
<?php if( is_active_sidebar('footer-map') ): ?>
<?php dynamic_sidebar('footer-map'); ?>
<?php endif; ?>
<div class="col-sm-12 col-md-12 col-lg-12 p-0 text-center credits-col">
<small><?php _e('Powered by '); ?><a class="" href=""><?php _e('UpAdv')?></a></small>
</div>
</div>
</div>
// this code is placed inside the main.js file of my theme
Vue.component('theme-nav',{
template: '#theme-nav',
props: {
//navId: Number
navlink: String,
}
});
Vue.component('theme-cover',{
template: '#theme-cover',
props: {
title: String,
src: String
}
});
const app = new Vue({
el: '#theme-vue',
data: {
postData: [],
navData: []
},
mounted: function(){
this.getMenu();
this.getIndex();
},
created: function(){
this.initParallax();
},
methods: {
initParallax: function(){
const parallax = new universalParallax();
},
getMenu: function(){
// this line didn't work, I need to get the custom logo but I don't know how with REST API?
axios.get('wp-json/theme/v1/logo').then( (response) => {
console.log(response);
});
axios.get('wp-json/theme/v1/menu').then( (response) => {
console.log(response);
response.data.forEach( (item, i) => {
this.navData.push(item);
});
});
},
getIndex: function(){
axios.get('wp-json/wp/v2/pages/?slug=home&_embed').then( (res) => {
console.log(res.data);
res.data.forEach( (item, i) => {
this.postData.push(item);
console.log(item._embedded['wp:featuredmedia'][0].source_url);
});
});
}
}
});
Try adding the navlink under data like
data: {
postData: [],
navData: [],
navlink:''
}

I am using Owl Carousel - Filter on projects as per category so i want to show the category description on every category button click

I have category table field and project table field in db i am fetching data or project as per category ID and showing them using php codedigniter in Owl Carousel - Filter Javascript.
below are the detail mention. include image view.
What actually i want i am trying to show the category detail under the projects on category button click
I assign the same class to the category button and the project by concatenating the category Id and projects category Id. So when we click on button the projects having same button class are appear perfectly but it not showing the category detail while click on specific category button click. for more information i am attaching my code as well. please have look. and help me. if you understand the problem.
my PHP Codeigniter Code is:
<div style="margin-bottom:10px; text-align: center;">
<div class="btn-filter-wrap">
<button class="btn-filter" data-filter="*">All</button>
<?php $categorydetail = ""; ?>
<?php if (!empty($categorydata)) { foreach ($categorydata as $category) {
$categoryclass = "category".($category['id']);
$categoryname = ($category['shortname']);
$categorydetail = ($category['detail']);
?>
<button class="btn-filter" data-filter=".<?php echo $categoryclass; ?>"><?php echo $categoryname; ?></button>
<?php }} ?>
</div>
<div class="project-slick categories">
<?php if (!empty($projectdata)) { foreach ($projectdata as $project) {
$projectclass = "category".($project['categoryid']);
$title = ($project['title']);
$detail = ($project['detail']);
$image = ($project['userfile']);
?>
<div class="item view view-eighth <?php echo $projectclass; ?>">
<img class="img-responsive" src="<?php echo base_url('fassets/images/projects/'. $image);?>" />
<div class="mask">
<h2><?= $title ?></h2>
<div><?php echo (strlen($project['detail'])>50)?(substr($project['detail'],0,200).'...'):$project['detail']; ?></div>
<a class="info ajax projects" href="<?php echo base_url("maincontroller/pdetail/".$project['id']);?>" >In Large</a>
</div>
</div>
<dir id="catdetail"><?= $categorydetail;?></dir>
<?php }} ?>
</div>
</div>
this is my javascript code is:
$(function() {
var owl = $('.categories').owlCarousel({
rel: 'gal',
width: "100%",
initialWidth: "0",
initialHeight: "0",
height:"100%",
// loop :false,
// margin :10,
// nav :false,
previous: "<i class='fa fa-chevron-left'></i>",
next: "<i class='fa fa-chevron-right'></i>",
close: "<i class='fa fa-times'></i>",
current: "",
responsive:{
0:{
items:1
},
600:{
items:2
},
1000:{
items:4
}
}
})
/* animate filter */
var owlAnimateFilter = function(even) {
$(this)
.addClass('__loading')
.delay(70 * $(this).parent().index())
.queue(function() {
$(this).dequeue().removeClass('__loading')
})
}
$('.btn-filter-wrap').on('click', '.btn-filter', function(e) {
var filter_data = $(this).data('filter');
/* return if current */
if($(this).hasClass('btn-active')) return;
/* active current */
$(this).addClass('btn-active').siblings().removeClass('btn-active');
/* Filter */
owl.owlFilter(filter_data, function(_owl) {
$(_owl).find('.item').each(owlAnimateFilter);
});
})
})
i solved this problem by creating javascript function
JS Func
function cat_detail(str) {
document.getElementById("cat_detail").innerHTML = str;
// alert(str);
}
After that i call event click on button and pass the string to the function.
<button class="btn-filter" onclick="cat_detail('<?= $categorydetail ?>')" data-filter=".<?php echo $categoryclass; ?>"><?php echo $categoryname; ?></button>
and create a div with ID "cat_detail" which display the detail. :)

bootstrap panels not collapsing

I've got a bootstrap accordion panel, and the panels aren't collapsing like they should when I click on them if they're already open. I can't figure out why. I had this working with the panels hard coded, but once I set up wp_query to load the panels, everything worked except the panels closing.
the function:
<script>
$(function () {
$('#accordion').on('shown.bs.collapse', function (e) {
var offset = $(this).find('.collapse.in').prev('.panel-heading');
if(offset) {
$('html,body').animate({
scrollTop: $(offset).offset().top -50
}, 500);
}
});
});
$('.collapse').on('shown.bs.collapse', function(){
$(this).parent().find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
}).on('hidden.bs.collapse', function(){
$(this).parent().find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
});
</script>
and the nested loops to generate the accordion panels:
<div class="home-contents">
<div class="container">
<div class="row">
<?php while ( have_posts() ) : the_post(); ?>
<h1 class="faqheading"><?php the_title(); ?></h1>
<!-- <div class="col-sm-9" style="float: none; margin: auto;"><?php the_content(); ?></div> -->
<?php endwhile; ?>
<div class="clear"></div>
</div> <!-- row -->
</div> <!-- container -->
<div class="blog-page">
<div class="container">
<div class="row">
<div class="col-sm-12 ">
<div class="container">
<div class="panel-group" id="accordion">
<?php
/*
* Loop through Categories and Display Posts within
*/
$post_type = 'faq';
// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) ); /* gets taxonomy from posts */
foreach( $taxonomies as $taxonomy ) :
// Gets every "category" (term) in this taxonomy to get the respective posts
$terms = get_terms( $taxonomy );
foreach( $terms as $term ) : ?>
<div class="groupheading col-sm-3"><h5 style=" color: #3fa9f5; font-size: 24px; font-weight: 300;"><?php echo $term->name; ?></h5></div>
<?php
$args = array(
'post_type' => $post_type,
'posts_per_page' => -1, //show all posts
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term->slug,
'orderby' => 'collapse id',
'order' => 'desc'
)
),
'order' => 'DESC'
);
?>
<?php
$posts = new WP_Query($args);
if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>
<div class="panel panel-default col-sm-9">
<div class="panel-heading">
<h4 class="panel-title">
<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#<?php echo 'collapse'.get_the_id();?>"><?php $value = get_field( "faq_heading"); echo $value; ?></a>
</h4>
</div>
<div id="<?php echo 'collapse'.get_the_id();?>" class="panel-collapse collapse">
<div class="panel-body col-sm-9">
<p><?php $value = get_field( "faq_text", false, false); echo $value; ?></p>
</div>
</div>
</div> <!-- .panel -->
<?php endwhile;?>
<div class="panel panel-default col-sm-9 mobilehide" style="height: 45px;"></div>
<div class="groupheading col-sm-3 mobilehide" style="height: 45px;"></div>
<?php
endif; ?>
<?php endforeach;
endforeach; ?>
</div> <!-- .panel-group -->
</div><!-- end col-sm-12 -->
</div> <!-- end row -->
</div><!-- end container -->
</div><!-- end blog-page -->
</div> <!-- .container -->
Edit: Ok, I've added the following but it's still not working:
<script>
$(document).ready(function(){
$("a.cf").click(function(){
$(this).parentsUntil(".panel-default").find(.children(".panel-collapse")).removeClass("in");
});f
});
</script>
2nd edit: I feel like the issue is that .parent isn't finding the right element, but I'm not sure how to direct it correctly.
<script>
$(document).ready(function(){
$("a.cf").click(function(){
$(this).addClass("collapsed");
$(this).parent().find(".panel-collapse .collapse").removeClass(".panel-collapse .collapse").addClass(".panel-collapse .collapse .in");
$(this).find().parent('.collapse.in').removeClass(".panel-collapse.collapse").addClass(".panel-collapse.collapse.in");;
});
});
</script>
Ok, I've solved this. I had originally built this page as part of a wordpress site, and I had included the bootstrap code at the top of the template. In the process of rebuilding the whole site, I put a new bootstrap include in the header file for the site. I left the old include at the top of my template when I got around to working on this particular page, and this redundancy of code was, somehow, causing the collapse to function incorrectly. I still don't know/understand why this was the case, but I've got it working correctly now.
I realize I didn't actually get any responses to this, but thank you to everyone who at least looked.

reload javascript code on every 10 sec

I have 3 progress bar on webpage from database data . When user click on load more 3 more progress bar get added from database data.
<div id="progressBar<?php echo $rec['cid'];?>" class="tiny-green"><div></div></div>
<!-- Some codes are here --->
...
....
.....
<?php
$prj= mysql_query("select * from campaign where uid=$uid");
$record = array();
while($row = mysql_fetch_assoc($prj)){
$record[] = $row;
}
?>
<script type="text/javascript">
<?php foreach($record as $rec){?>
progressBar(<?php $perc= $rec['value']*100/$rec['value1']; echo $perc;?>, $('#progressBar<?php echo $rec['cid'];?>'));
<?php } ?>
</script>
Below is javascript plugin
<script type="text/javascript" src="js/jquery.countdown.min.js"></script>
Now problem is when i add progress bar from load_more button(Which get data by load_more.php file and it insert it on index.php file). i can see the value but progress bar is not creating because code given above not loading after clicking on load_more.
So, i want to know is there any way i can reload that code only. So, wherever there is a progress bar control placed it get the display the bar.
update with some modifications, hope it will help you
$prj= mysql_query("select * from campaign where uid=$uid order by Closing_Date DESC Limit 0,1");
$result = array('data' => '', 'progress_bar' => array());
while($row = mysql_fetch_assoc($prj)) {
$result['data'] .= '<div class="col-sm-1 col-md-4 unique" id="'.$rec['cid'].'">
<div class="well">
<div class="media services-wrap55 wow fadeInDown">
<img class="img-responsive" src="'.$rec['poster'].'"><br>
<h4 class="media-heading">'.$rec['project_Name'].'</h4>
<p> by <i>'.$rec['user_name'].'</i></p>
<p> '.$rec['short_dis'].'</p>
<a class="" href="view_project/'.$rec['cid'].'/'.$rec['slug'].'">More ... </a>
<p>
<div id="progressBar'.$rec['cid'].'" class="tiny-green"><div></div></div>
<h6>'.($rec['view']*100/$rec['view2']).'% ( <i class="fa fa-user"></i>'.$rec['view']. ') '.$rec['view2'].' views.</h6>
</p>
<div class="counter-inner"> <div id="example1" data-countdown="'.date("m/d/Y h:i:s", strtotime($rec['Closing_Date'])).'"></div></div><p> <!-- Work on this -->
<div class="col-sm-11">
<div class="entry-meta">
<span><font color="#339933"><i class="fa fa-comment"></i> </font> '.$rec['comment'].' Comments </a></span><!-- Work on this -->
<span><font color="#339933"><i class="fa fa-thumbs-up"></i></font> '.$rec['up_count'].' </a></span>
<span><font color="#339933"><i class="fa fa-thumbs-down"></i></font> '.$rec['down_count'].' </a></span>
<span><font color="#339933"><i class="fa fa-star"></i> </font> '.$rec['fav_count'].' Fav </a></span>
</div>
</div>
</div>
</div>
</div>';
$result['progress_bar'][] = array('cid' => $rec['cid'], 'perc' => $rec['value'] * 100 / $rec['value1']);
}
$(document).ready(function() {
$('#more').click(function() {
var get_last_post_display = $('.unique-class:last').attr('id'); //get ip last <li>
$('#more').html('<img src="ajax-loader.gif"');
$.post('more_prj.php', 'last_id_post='+get_last_post_display, function(html) {
if(html.data) {
$('div').append(html.data);//$('.main-div') ?
$('#more').text('Load More Project'); //add text "Load More Post" to button again
for(i = 0; i < html.progress_bar.length; i++) {
progressBar(html.progress_bar[i]['perc'], $('#progressBar' + html.progress_bar[i]['cid']));
}
} else {
$('#more').text('No more Project to load'); // when last record add text "No more posts to load" to button.
}
}, 'json');
});
});

Categories