How to auto-scroll to specific element using JavaScript - javascript

I'm creating simple quiz plugin, but now I'm in dilemma, because don't have an idea how to make options to auto-scroll to the top of the Explanation Box after visitor choose an answer (right or wrong, explanation box is same with same content. Note - explainer box is hidden until visitor clicks with mouse on checkbox of any offered answer.
Below is JavaScript code I have so far:
var wpvqgr = wpvqgr || {};
(function($)
{
$(document).ready(function()
{
wpvqgr.selectAnswer = function($question, question_id, $answer, answer_id)
{
// Don't let the user play twice the same question!
if ($answer.hasClass('wpvqgr-disabled-answer') && !wpvqgr.vars.quiz.settings.trivia_hiderightwrong) {
return;
}
// Right or wrong?
var rightAnswers = wpvqgr.getRightAnswers(question_id);
var isRight = (rightAnswers.indexOf(answer_id) > -1);
// Store data
var _answers = wpvqgr.getStore('answers') || { 'questions' : [] };
_answers.questions[question_id] = {
'answer_id' : answer_id,
'isRight' : isRight,
'rightAnswers' : rightAnswers,
};
wpvqgr.setStore('answers', _answers);
// Display Right or Wrong answers
if (wpvqgr.vars.quiz.settings.trivia_hiderightwrong != 'yes')
{
// First, disable every answers
$question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer').addClass('wpvqgr-disabled-answer');
// Add explanation
var $explanation = $question.find('div.wpvqgr-explanation');
$explanation.find('div.wpvqgr-explanation-content').html(wpvqgr.vars.quiz.questions[question_id].wpvqgr_quiz_questions_explanation);
if (isRight)
{
$explanation.find('h3.wpvqgr-thats-right').show();
$answer.addClass('wpvqgr-right-answer');
}
else
{
$explanation.find('h3.wpvqgr-thats-wrong').show();
$answer.addClass('wpvqgr-wrong-answer');
$.each(rightAnswers, function(index, answer_id){
$question.find('.wpvqgr-answer[data-id=' + answer_id + ']').addClass('wpvqgr-right-answer');
});
}
$explanation.show();
}
else
{
$question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer');
$answer.addClass('wpvqgr-selected-answer');
}
// Update visual checkbox
$question.find('div.wpvqgr-checkbox-picture').removeClass('wpvqgr-checkbox-checked-picture');
$answer.find('div.wpvqgr-checkbox-picture').addClass('wpvqgr-checkbox-checked-picture');
// Not a visual class, just marked as
$answer.addClass('wpvqgr-is-selected-answer');
};
wpvqgr.computeResults = function()
{
var answers = wpvqgr.getStore('answers') || { 'questions' : [] };
var finalScore = 0;
// Score
$.each(answers.questions, function (q_id, answer_data) {
if (answer_data.isRight) {
finalScore++;
}
});
// Appreciation
var appreciation = wpvqgr.getAppreciation(finalScore);
// Store global data for Facebook, page refresh and other stuff
wpvqgr.setStore('finalScore', finalScore);
wpvqgr.setStore('appreciation', appreciation);
};
//Autoscroll
/**
* Integrate results in view
* #return {[type]} [description]
*/
wpvqgr.integrateResults = function ()
{
wpvqgr.parseResults('quizname', wpvqgr.vars.quiz.general.name);
wpvqgr.parseResults('score', wpvqgr.getStore('finalScore'));
wpvqgr.parseResults('total', wpvqgr.getStore('answers').questions.length);
wpvqgr.parseResults('description', wpvqgr.getStore('appreciation').content);
}
wpvqgr.getAppreciation = function(score)
{
var finalAppreciationId = -1;
var finalAppreciationScoreStep = 9999;
$.each(wpvqgr.vars.quiz.appreciations, function (ap_id, data)
{
var app_score = parseInt(data.score);
if (score <= app_score && finalAppreciationScoreStep > app_score)
{
finalAppreciationScoreStep = app_score;
finalAppreciationId = ap_id;
}
});
// No appreciation found!
if (finalAppreciationId == -1) {
return { 'content':'', 'redirect':'', 'picture':'', 'score':-1 }
} else {
return wpvqgr.vars.quiz.appreciations[finalAppreciationId];
}
};
wpvqgr.getRightAnswers = function(question_id)
{
var rightAnswers = [];
var answers = wpvqgr.vars.quiz.questions[question_id]['wpvqgr_quiz_questions_answers'];
$.each(answers, function(id, data) {
if (data['wpvqgr_quiz_questions_answers_right']) {
rightAnswers.push(id);
}
});
return rightAnswers;
};
wpvqgr.getFinalScore = function()
{
return wpvqgr.getStore('finalScore');
};
});
})(jQuery);
/**
* Store
*
* questions[$id] = $answer_id
*
*
*
*/
<?php global $wpvqgr_quiz, $wpvqgr_quiz_columns, $wpvqgr_resources_dir_url, $wpvqgr_skin_dir_url; ?>
<!-- Load CSS Skin Theme -->
<style> #import url('<?php echo $wpvqgr_resources_dir_url . 'css/bootstrap-wrapper.css'; ?>'); </style>
<style> #import url('<?php echo $wpvqgr_resources_dir_url . 'icons/fa/css/font-awesome.min.css'; ?>'); </style>
<style> #import url('<?php echo $wpvqgr_resources_dir_url . 'css/fo-style.css'; ?>'); </style>
<style> #import url('<?php echo $wpvqgr_skin_dir_url . 'style.css'; ?>'); </style>
<!-- Custom style -->
<style>
<?php if ($wpvqgr_quiz->getSetting('progessbarcolor') != ''): ?>
.wpvqgr-wrapper button.wpvqgr-button.wpvqgr-playagain,
.wpvqgr-wrapper button.wpvqgr-button.wpvqgr-start-button,
.wpvqgr-wrapper div.wpvqgr-continue button.wpvqgr-button,
.wpvqgr-wrapper button.wpvqgr-button.wpvqgr-askinfo-submit,
.wpvqgr-progress .progress-bar {
background-color:<?php echo $wpvqgr_quiz->getSetting('progessbarcolor'); ?>;
}
<?php endif; ?>
<?php echo $wpvqgr_quiz->getSetting('global_custom_css'); ?>
</style>
<!-- Facebook SDK -->
<script type="text/javascript">
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<!-- / Prepare sharing options -->
<?php echo apply_filters('wpvqgr_public_version', "<!-- Quiz Created with WP Viral Quiz (v".WPVQGR_VERSION.") - https://www.ohmyquiz.io/discover -->"); ?>
<a name="wpvqgr"></a>
<div class="wpvqgr-wrapper">
<div class="container-fluid">
<?php if ($wpvqgr_quiz->getSetting('startbutton') && !$wpvqgr_resultsOnly): ?>
<div class="wpvqgr-intro">
<?php if ($wpvqgr_quiz->getSetting('startbuttonintro')): ?>
<p><?php echo $wpvqgr_quiz->getSetting('startbuttonintro'); ?></p>
<?php endif ?>
<button class="wpvqgr-start-button wpvqgr-button"><?php echo $wpvqgr_quiz->getSetting('customlabel_startbutton'); ?></button>
</div>
<?php endif ?>
<div id="wpvqgr-<?php echo $wpvqgr_quiz->getId(); ?>" class="wpvqgr <?php echo $wpvqgr_quiz->getType(); ?>">
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_before')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_before')); ?>
</div>
<?php if ($wpvqgr_quiz->getPageCounter() > 1 && in_array('top', $wpvqgr_quiz->getSetting('progessbar'))): ?>
<!-- Progress bar -->
<div class="wpvqgr-progress wpvqgr-progress-top progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<?php endif ?>
<?php if (!$wpvqgr_resultsOnly): ?>
<div class="wpvqgr-page-0 wpvqgr-page" data-id="0">
<?php
$wpvqgr_questions = $wpvqgr_quiz->getQuestionsAndBlocks();
$q_real_id = -1;
foreach($wpvqgr_questions as $q_id => $question):
// Type and content
$q_type = $question['_type'];
$q_content = ($q_type == 'wpvqgr_quiz_htmlblocks') ? $question['wpvqgr_quiz_htmlblocks_content'] : $question['wpvqgr_quiz_questions_content'];
// Real ID (ignore HTML blocks)
if ($q_type == 'wpvqgr_quiz_questions') {
$q_real_id++;
}
// Pagination
$q_isTherePage = ($question['wpvqgr_quiz_questions_addpage'] && isset($wpvqgr_questions[$q_id+1]));
$currentPage_id = (!isset($currentPage_id)) ? 0 : $currentPage_id;
// Picture
if ($q_type == 'wpvqgr_quiz_questions') {
$q_picture_id = $question['wpvqgr_quiz_questions_picture'];
$q_picture_info = WPVQGR_Snippets::wpGetAttachment($q_picture_id);
$q_picture_url = wp_get_attachment_url($q_picture_id);
}
?>
<div class="row">
<div class="col-sm-12">
<!-- Global ads between questions -->
<?php if ( $q_real_id > 0 && $wpvqgr_quiz->getSetting('global_ads_between_count') > 0 && ($q_real_id % $wpvqgr_quiz->getSetting('global_ads_between_count') == 0) ): ?>
<?php echo $wpvqgr_quiz->getSetting('global_ads_between_content'); ?>
<?php endif; ?>
<!-- HTML Blocks -->
<?php if ($q_type == 'wpvqgr_quiz_htmlblocks'): ?>
<div class="wpvqgr-htmlblock">
<?php echo do_shortcode($q_content); ?>
</div>
<?php else: ?>
<!-- Regular question -->
<div class="wpvqgr-question" data-id="<?php echo $q_real_id; ?>">
<div class="wpvqgr-question-label"><?php echo do_shortcode(nl2br($q_content)); ?></div>
<?php if (is_numeric($q_picture_id)): ?>
<div class="wpvqgr-question-picture">
<figure class="figure">
<img src="<?php echo $q_picture_url; ?>" class="figure-img img-fluid" alt="<?php echo htmlentities($q_picture_info['alt']); ?>" />
<?php if ($q_picture_info['caption'] != ''): ?>
<figcaption class="figure-caption"><?php echo $q_picture_info['caption']; ?></figcaption>
<?php endif; ?>
</figure>
<?php if (function_exists ('adinserter')) echo adinserter (1); ?> <!-- / First Add Code -->
</div>
<?php endif ?>
<div class="row">
<?php
$smartColumns = WPVQGR_Snippets::getSmartColumnsSize($question, $wpvqgr_quiz_columns);
foreach ($question['wpvqgr_quiz_questions_answers'] as $a_id => $answer):
// Answer
$a_label = $answer['wpvqgr_quiz_questions_answers_answer'];
// Picture
if ($smartColumns['displayPicture'])
{
$a_picture_id = $answer['wpvqgr_quiz_questions_answers_picture'];
if ($a_picture_id == 0) {
$a_picture_info = array('alt' => '', 'caption' => '');
$a_picture_url = WPVQGR_PLUGIN_URL . '/resources/images/picture-placeholder.jpg';
} else {
$a_picture_info = WPVQGR_Snippets::wpGetAttachment($a_picture_id);
$a_picture_url = wp_get_attachment_image_src($a_picture_id, 'wpvqgr-square-answer');
$a_picture_url = $a_picture_url[0];
}
}
?>
<div class="wpvqgr-answer-col col-xs-<?php echo $smartColumns['xs-size']; ?> col-md-<?php echo $smartColumns['md-size']; ?>">
<div class="wpvqgr-answer" data-id="<?php echo $a_id; ?>">
<?php if ($wpvqgr_quiz->getType() == 'wpvqgr_quiz_perso'): ?>
<!-- Multipliers -->
<?php foreach ($answer['wpvqgr_quiz_questions_answers_multipliers'] as $p_id => $value): ?>
<input type="hidden" name="wpvqgr_answer_multipliers[]" data-pid="<?php echo (int)$p_id; ?>" value="<?php echo (int)$value; ?>" />
<?php endforeach ?>
<?php endif; ?>
<?php if ($smartColumns['displayPicture']): ?>
<div class="wpvqgr-answer-picture">
<figure class="figure">
<img src="<?php echo $a_picture_url; ?>" class="figure-img img-fluid" alt="<?php echo htmlentities($a_picture_info['alt']); ?>" />
<?php if ($a_picture_info['caption'] != ''): ?>
<figcaption class="figure-caption"><?php echo $a_picture_info['caption']; ?></figcaption>
<?php endif; ?>
</figure>
</div>
<?php endif ?>
<?php if ($a_label != ''): ?>
<div class="wpvqgr-checkbox">
<div class="wpvqgr-checkbox-picture wpvqgr-checkbox-unchecked-picture"></div>
<span class="wpvqgr-answer-label"><?php echo do_shortcode(stripslashes($a_label)); ?></span>
<hr class="wpvqgr-clear" />
</div>
<?php endif ?>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="row"><div class="col-sm-12">
<div class="wpvqgr-explanation">
<center><h6>⇩ SCROLL DOWN TO CONTINUE ⇩</h6></center>
<h3 class="wpvqgr-thats-right"><?php echo $wpvqgr_quiz->getSetting('customlabel_right'); ?></h3>
<h3 class="wpvqgr-thats-wrong"><?php echo $wpvqgr_quiz->getSetting('customlabel_wrong'); ?></h3>
<div class="wpvqgr-explanation-content"></div>
</div>
</div>
</div>
</div> <!-- .question -->
<?php endif; ?>
</div> <!-- / col -->
</div> <!-- / row -->
<div class="autoscroll>">
</div>
<div class="wpvqgr-continue">
<?php if (function_exists ('adinserter')) echo adinserter (2); ?> <!-- / Second Add Code -->
<button class="wpvqgr-button" style="background:<?php echo $wpvqgr_quiz->getSetting('progessbarcolor'); ?>;">
<?php echo $wpvqgr_quiz->getSetting('customlabel_continuebutton'); ?>
</button>
</div>
<?php
if ($q_isTherePage): $currentPage_id++;
?>
</div> <!-- close previous page -->
<div class="wpvqgr-page-<?php echo $currentPage_id; ?> wpvqgr-page" data-id="<?php echo $currentPage_id; ?>">
<?php endif ?>
<?php endforeach; ?>
</div> <!-- Final page close -->
<?php endif; ?>
<a id="wpvqgr-resultarea"></a>
<!-- Force to share -->
<div class="row">
<div class="col-xs-12 col-md-10 offset-md-1">
<div class="wpvqgr-forcetoshare">
<h3><?php echo __("Share the quiz to show your results !", 'wpvq'); ?></h3>
<button class="wpvqgr-button wpvqgr-social-facebook wpvqgr-force-share" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_description'); ?>"><i class="fa fa-facebook-square" aria-hidden="true"></i> <?php echo __('Share on Facebook', 'wpvq'); ?></button>
</div>
</div>
</div>
<!-- Force to give some informations -->
<div class="row">
<div class="col-xs-12 col-md-10 offset-md-1">
<div class="wpvqgr-askinfo">
<h3><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfotitle'); ?></h3>
<form action="" method="GET">
<?php foreach($wpvqgr_quiz->getSetting('askinfo_fields') as $field): ?>
<?php
$field_slug = WPVQGR_Snippets::slugify($field['wpvqgr_settings_askinfo_fields_field_label']);
$is_required_field = ($field['wpvqgr_settings_askinfo_fields_field_optional'] != 'yes');
?>
<div class="form-group">
<label for="wpvqgr-<?php echo $field_slug; ?>"><?php echo $field['wpvqgr_settings_askinfo_fields_field_label']; ?></label>
<input type="<?php echo $field['wpvqgr_settings_askinfo_fields_field_type']; ?>" class="form-control" name="<?php echo $field_slug; ?>" id="wpvqgr-<?php echo $field_slug; ?>" <?php if($is_required_field): ?>required="true"<?php endif; ?>/>
</div>
<?php endforeach; ?>
<?php if ($wpvqgr_quiz->getSetting('global_gdpr_enabled') == 1): ?>
<div class="form-check gdpr-area">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="wpvq_gpdr" id="wpvq_gpdr_checkbox" required="true" />
<?php echo $wpvqgr_quiz->getSetting('global_gdpr_message'); ?>
</label>
</div>
<?php endif ?>
<div class="form-group" style="text-align:center;">
<button type="submit" class="wpvqgr-button wpvqgr-askinfo-submit"><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfobutton'); ?></button>
</div>
</form>
<?php if ($wpvqgr_quiz->getSetting('askinfo_ignore')): ?>
<p class="wpvqgr-askinfo-ignore"><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfoignore'); ?></p>
<?php endif ?>
</div>
</div>
</div>
<!-- Show results -->
<div class="row">
<div class="col-sm-12">
<div class="wpvqgr-results">
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_aboveresults')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_aboveresults')); ?>
</div>
<div class="wpvqgr-results-box <?php echo $wpvqgr_quiz->getType(); ?>">
<div class="wpvqgr-top-result">
<div class="wpvqgr-quiz-name"><?php echo stripslashes($wpvqgr_quiz->getName()); ?></div>
<h3><?php echo $wpvqgr_quiz->getSetting('global_template_result'); ?></h3>
<div class="wpvqgr-result-description">%%description%%</div>
</div>
<div class="wpvqgr-additional-results">
<div class="wpvqgr-additional-results-template">
<h3><?php echo $wpvqgr_quiz->getSetting('global_template_additional_results'); ?></h3>
<div class="wpvqgr-result-description">%%description%%</div>
</div>
</div>
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_afterresults')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_afterresults')); ?>
</div>
<?php if ($wpvqgr_quiz->getSetting('displaysharing')): ?>
<div class="wpvqgr-sharing">
<?php if (!in_array('facebook', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
<button class="wpvqgr-button wpvqgr-social-facebook" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_description'); ?>"><i class="fa fa-facebook-square" aria-hidden="true"></i> <?php echo __('Share on Facebook', 'wpvq'); ?></button>
<?php endif; ?>
<!-- Twitter -->
<?php if (!in_array('twitter', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
<button class="wpvqgr-button wpvqgr-social-twitter" data-tweet="<?php echo $wpvqgr_quiz->getSetting('global_template_twitter'); ?>" data-mention="<?php echo $wpvqgr_quiz->getSetting('twittermention'); ?>" data-hashtag="<?php echo $wpvqgr_quiz->getSetting('twitterhashtag'); ?>"><i class="fa fa-twitter-square" aria-hidden="true"></i> <?php echo __('Share on Twitter', 'wpvq'); ?></button>
<?php endif ?>
<!-- VK -->
<?php if (!in_array('vk', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
<button class="wpvqgr-button wpvqgr-social-vk" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_vk_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_vk_description'); ?>"><i class="fa fa-vk" aria-hidden="true"></i> <?php echo __('Share on VK', 'wpvq'); ?></button>
<?php endif ?>
</div>
<?php endif; ?>
</div>
<?php if ($wpvqgr_quiz->getSetting('playagain')): ?>
<button class="wpvqgr-button wpvqgr-playagain"><?php echo $wpvqgr_quiz->getSetting('customlabel_playagainbutton'); ?></button>
<?php endif; ?>
</div>
</div>
</div>
<?php if ($wpvqgr_quiz->getPageCounter() > 1 && in_array('bottom', $wpvqgr_quiz->getSetting('progessbar'))): ?>
<!-- Progress bar -->
<div class="wpvqgr-progress wpvqgr-progress-bottom progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<?php endif ?>
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_after')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_after')); ?>
</div>
<?php if ($wpvqgr_quiz->getSetting('promote')): ?>
<div class="wpvqgr-promote">
<p>
<?php _e("This quiz has been created with", 'wpvq'); ?> WordPress Viral Quiz
</p>
</div>
<?php endif; ?>
</div> <!-- / #wpvqgr -->
</div> <!-- / container -->
<!-- Loading -->
<div class="row">
<div class="wpvqgr-loader">
<p>
<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i>
<span class="sr-only"><?php _e("Loading...", 'wpvq'); ?></span>
</p>
</div>
</div>
</div> <!-- / Bootstrap wrapper -->
I tried with dummy DIV element, but without success (to have it as an anchor, because explainer element is invisible).
Code samples I tried so far are:
$('wpvqgr-answer').click(function() {
$('html,body').animate({scrollTop: ('#autoscroll').offset().top - staticHeaderHeight}, 'slow');
return true;
});
And:
$('.wpvqgr-answer').click(function () {
$("html, body").animate({ scrollTop: $(el).closest(':visible').offset().top}, 400);
return true;
});
And, this was desperate act of self destruction:
$('.wpvqgr-answer').click(() => {
$('.wpvqgr-explanation').toggle('smooth', () => {
$('.wpvqgr-explanation').get(0).scrollIntoView();
});
});
I hope you have some kind of overview now, even in basic sense. Any guidance appreciated. Thank you
EDIT: Box creation conditions are within JS and parsed to HTML code, example below:
// Add explanation
var $explanation = $question.find('div.wpvqgr-explanation');
$explanation.find('div.wpvqgr-explanation-content').html(wpvqgr.vars.quiz.questions[question_id].wpvqgr_quiz_questions_explanation);
if (isRight)
{
$explanation.find('h3.wpvqgr-thats-right').show();
$answer.addClass('wpvqgr-right-answer');
}
else
{
$explanation.find('h3.wpvqgr-thats-wrong').show();
$answer.addClass('wpvqgr-wrong-answer');
$.each(rightAnswers, function(index, answer_id){
$question.find('.wpvqgr-answer[data-id=' + answer_id + ']').addClass('wpvqgr-right-answer');
});
}
$explanation.show();
}
else
{
$question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer');
$answer.addClass('wpvqgr-selected-answer');
}
<div class="row"><div class="col-sm-12">
<div class="wpvqgr-explanation">
<center><h6>⇩ SCROLL DOWN TO CONTINUE ⇩</h6></center>
<h3 class="wpvqgr-thats-right"><?php echo $wpvqgr_quiz->getSetting('customlabel_right'); ?></h3>
<h3 class="wpvqgr-thats-wrong"><?php echo $wpvqgr_quiz->getSetting('customlabel_wrong'); ?></h3>
<div class="wpvqgr-explanation-content"></div>
</div>
</div>
</div>

Simple piece of code worked as charm for me, just enough to achieve functionality and in the same time not to complicate too much:
const goToTop = () => window.scrollTo(0, 950);
goToTop();
This is very quick and "clean" solution for one who does not need complicated function.

Related

codeigniter call function with jquery no reload

i am reading and trying to get this to work for several hours. I am pretty new with javascript and only have a small knowledge base about it in general.
I hope someone can be so kind as to help me and share their knowledge with me.
The problem:
I have a image gallery with a php generated masonry look. And a visualization of either a selected or deselected image. (Info comes out of db). Now when i click a image it needs to call a method in one of my controllers.
And afterwards update the selected to deselected or vise versa css style.
The methods have been made and the return aswell.
This is what i got so far. But nothing seems to be working. I don't know if it is something specific to codeigniter or to javascript (jquery).
$(document).ready(function()
{
$('div#imagelink').click(function()
{
var imgId = $(this).find('a').attr('href');
$('#result').load('<?php echo base_url(); ?>selection/selectionImage/' + imgId);
return false;
});
});
If anything else is required i will be happy to provide.
<div class="flex-column width-1275">
<div class="d-flex justify-content-between">
<div class="p-2">
<h1><?php echo $this->session->userdata('username'); ?></h1>
<h3><?php echo str_replace( '_', ' ', $selected_gallery) . ' Galerij'; ?></h3>
</div>
<?php echo $this->session->flashdata('gallerymsg'); ?>
<div class="p-2 text-right">
<?php echo $this->session->flashdata('clientmsg') . '</br>'; ?>
</div>
<div id="result"></div>
</div>
<div class="grid imageGallery" data-masonry='{ "itemSelector": ".grid-item", columnWidth: ".grid-sizer" }'>
<div class="grid-sizer"></div>
<?php $counter=1 ; $sizeGallery=c ount($images); foreach($images as $img) : $imageLocation='img/jpg/' . $folderName . '/' . $img[ 'image_name']; $id=$ selected_gallery . $counter; ?>
<div class="grid-item">
<a href="#<?php echo $id; ?>">
<img src="<?php echo base_url($imageLocation) ?>" alt="<?php echo $selected_gallery . ' ' . $counter ?>">
</a>
<?php $class='' ; $selected=$ img[ 'image_selected']; switch($selected) { case '0'; $class='isNot' ; break; case '1'; $class='is' ; break; default; $class='isNot' ; break; } if($img[ 'image_locked']=='1' ) { $class='locked' ; } ?>
<div id="imagelink" class="<?php echo $class ?> selected">
<?php if ($img[ 'image_locked']=='0' ) : ?>
<!-- -->
<?php endif; ?>
</div>
</div>
<div class="cssbox">
<a id="<?php echo $id; ?>" href="#<?php echo $id; ?>">
<img class="cssbox_thumb">
<span class="cssbox_full">
<img src="<?php echo base_url($imageLocation) ?>">
</span>
<div class="<?php echo $class ?> Lightbox-Selected"></div>
</a>
<a class="cssbox_close" href="#void"></a>
<?php if($counter < $sizeGallery) : ?>
<?php $next=$ counter+1; ?>
<a class="cssbox_next" href="#<?php echo $selected_gallery . $next ?>">></a>
<?php endif; ?>
<?php if($counter> 1) : ?>
<?php $prev=$ counter-1; ?>
<a class="cssbox_prev" href="#<?php echo $selected_gallery . $prev ?>"><</a>
<?php endif ?>
</div>
<?php $counter++; endforeach; ?>
</div>
</div>
<script>
$(document).ready(function() {
$('div#imagelink').click(function() {
var imgId = $(this).find('a').attr('href');
$('#result').load('<?php echo base_url(); ?>selection/selectionImage/' + imgId);
return false;
});
});
</script>
<!-- <script src="<?php echo base_url('assets/js/image-select.js'); ?>"></script> -->
<script src="<?php echo base_url('assets/js/imagesloaded.pkgd.js'); ?>"></script>
<script src="<?php echo base_url('assets/js/masonry.pkgd.js'); ?>"></script>
<script src="<?php echo base_url('assets/js/masonry.js'); ?>"></script>

Issue in download div as a PDF using javascript?

I am trying to download specific div as a PDF but it is not showing complete part of the div.it is only showing first two columns and not showing complete height and width of the div. How can i export complete div with HTML output of the div?. it will be better if page is directly mail to receiver in PDF format.
my div is look like this
[1]: [https://i.stack.imgur.com/9t012.png][1]
after export it in pdf it looking like this
[2]: [https://i.stack.imgur.com/eReu9.png][1]
my code is,
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script type="text/javascript" src="jspdf.min.js"></script>
<script type="text/javascript">
function genPDF()
{
html2canvas(document.body,{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img,'JPEG',20,20);
doc.save('test.pdf');
}
});
}
</script>
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<div class="my-wishlist">
<div class="page-title title-buttons">
<?php if ($this->helper('wishlist')->isRssAllow() && $this->hasWishlistItems()): ?>
<?php echo $this->__('RSS Feed') ?>
<?php endif; ?>
<h1><?php echo $this->getTitle(); ?></h1>
</div>
<?php echo $this->getMessagesBlock()->toHtml() ?>
<form id="wishlist-view-form" action="<?php echo $this->getUrl('*/*/update', array('wishlist_id' => $this->getWishlistInstance()->getId())) ?>" method="post">
<?php echo $this->getChildHtml('top'); ?>
<div class="fieldset">
<?php if ($this->hasWishlistItems()): ?>
<?php echo $this->getBlockHtml('formkey');?>
<?php $this->getChild('items')->setItems($this->getWishlistItems()); ?>
<?php echo $this->getChildHtml('items');?>
<script type="text/javascript">decorateTable('wishlist-table')</script>
<?php else: ?>
<p class="wishlist-empty"><?php echo $this->__('You have no items in your quote.') ?></p>
<?php endif ?>
<div class="buttons-set buttons-set2">
<?php echo $this->getChildHtml('control_buttons');?>
</div>
</div>
</form>
<form id="wishlist-allcart-form" action="<?php echo $this->getUrl('*/*/allcart') ?>" method="post">
<?php echo $this->getBlockHtml('formkey') ?>
<div class="no-display">
<input type="hidden" name="wishlist_id" id="wishlist_id" value="<?php echo $this->getWishlistInstance()->getId() ?>" />
<input type="hidden" name="qty" id="qty" value="" />
</div>
</form>
<script type="text/javascript">
//<![CDATA[
var wishlistForm = new Validation($('wishlist-view-form'));
var wishlistAllCartForm = new Validation($('wishlist-allcart-form'));
function calculateQty() {
var itemQtys = new Array();
$$('#wishlist-view-form .qty').each(
function (input, index) {
var idxStr = input.name;
var idx = idxStr.replace( /[^\d.]/g, '' );
itemQtys[idx] = input.value;
}
);
$$('#qty')[0].value = JSON.stringify(itemQtys);
}
function addAllWItemsToCart() {
calculateQty();
wishlistAllCartForm.form.submit();
}
//]]>
</script>
</div>
Download PDF
<?php echo $this->getChildHtml('bottom'); ?>
<div class="buttons-set">
<p class="back-link"><small>« </small><?php echo $this->__('Back') ?></p>
</div>
<?php endif ?>
Thanks in advance
This is exact div which i am trying to export
<div class="my-wishlist">
<div class="page-title title-buttons">
<?php if ($this->helper('wishlist')->isRssAllow() && $this->hasWishlistItems()): ?>
<?php echo $this->__('RSS Feed') ?>
<?php endif; ?>
<h1><?php echo $this->getTitle(); ?></h1>
</div>
<?php echo $this->getMessagesBlock()->toHtml() ?>
<form id="wishlist-view-form" action="<?php echo $this->getUrl('*/*/update', array('wishlist_id' => $this->getWishlistInstance()->getId())) ?>" method="post">
<?php echo $this->getChildHtml('top'); ?>
<div class="fieldset">
<?php if ($this->hasWishlistItems()): ?>
<?php echo $this->getBlockHtml('formkey');?>
<?php $this->getChild('items')->setItems($this->getWishlistItems()); ?>
<?php echo $this->getChildHtml('items');?>
<script type="text/javascript">decorateTable('wishlist-table')</script>
<?php else: ?>
<p class="wishlist-empty"><?php echo $this->__('You have no items in your quote.') ?></p>
<?php endif ?>
<div class="buttons-set buttons-set2">
<?php echo $this->getChildHtml('control_buttons');?>
</div>
</div>
</form>
<form id="wishlist-allcart-form" action="<?php echo $this->getUrl('*/*/allcart') ?>" method="post">
<?php echo $this->getBlockHtml('formkey') ?>
<div class="no-display">
<input type="hidden" name="wishlist_id" id="wishlist_id" value="<?php echo $this->getWishlistInstance()->getId() ?>" />
<input type="hidden" name="qty" id="qty" value="" />
</div>
</form>
<script type="text/javascript">
//<![CDATA[
var wishlistForm = new Validation($('wishlist-view-form'));
var wishlistAllCartForm = new Validation($('wishlist-allcart-form'));
function calculateQty() {
var itemQtys = new Array();
$$('#wishlist-view-form .qty').each(
function (input, index) {
var idxStr = input.name;
var idx = idxStr.replace( /[^\d.]/g, '' );
itemQtys[idx] = input.value;
}
);
$$('#qty')[0].value = JSON.stringify(itemQtys);
}
function addAllWItemsToCart() {
calculateQty();
wishlistAllCartForm.form.submit();
}
//]]>
</script>
</div>

Can't pass target ID in hide/show function

I have a "read more about supplier" displayed on each productarticle. When you click it, it's supposed to pop-up a small box with information about the supplier.
The code is working, but when you click the text it only toggles the productarticle on the top of the page. It looks like it can't seperate them and give them each a unique ID. I have no idea how to do this as I'm an amateur. Any help please?
HTML:
<div class="popup" onclick="myFunction1()" style="position:relative; left:
70px;">Read more about <?php echo $supplier ?> here
<span class="popuptext" id="myPopup">
<b><?php $a = strtolower($supplier); if (strpos($a, 'supplier1') !== false) { echo 'Supplier 1 description'; } ?></b>
<b><?php $a = strtolower($supplier); if (strpos($a, 'supplier2') !== false) { echo 'Supplier 2 description'; } ?></b>
<b><?php $a = strtolower($supplier); if (strpos($a, 'supplier3') !== false) { echo 'Supplier 3 description'; } ?></b>
</span>
</div>
js:
function myFunction1() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
the loop including all products:
<?php $hr='';?>
<div class="row">
<ul class="listProductItems clearfix">
<?php for ($art=0; $art<count($articles); $art++){ ?>
<?php $imagine =$this->site_model->show_thumbs($articles[$art]['LA_ART_ID']); ?>
<?php $supplier =(($articles[$art]['producer']!==NULL) ? $articles[$art]['producer'] : $articles[$art]['SUP_BRAND']); ?>
<?php //$criteria =$this->site_model->article_criteria($articles[$art]['LA_ART_ID'],$articles[$art]['ga_id']); ?>
<?php $criteria =$this->site_model->article_criteria_filter($articles[$art]['la_id']); ?>
<?php $criteria .=$this->site_model->article_criteria($articles[$art]['LA_ART_ID'],$articles[$art]['ga_id']); ?>
<?php if ($hr !== $articles[$art]['generic_name'].' PRODUCED BY '.$supplier){ ?>
<div class="clearfix"></div>
<?php $hr = $articles[$art]['generic_name'].' PRODUCED BY '.$supplier; ?>
<?php } ?>
<li class="clearfix">
<div class="span4" style="max-height:50px">
<?php if (isset($imagine)){ ?>
<div class="thumbnail"><?php echo $imagine; ?></div>
<?php } else { ?>
<div class="thumbnail"><a href="<?php echo site_url('type/'.$versiune.'/category/'.$tree.'/article/'.$articles[$art]['la_id']); ?>">

gallery post filter with pagination not working

I have create post gallery and I have used 4 type of taxonomy also I want to filter all posts with pagination but my filter is not working properly. when I have select model -> ford then posts is not display in 1st page there is display in 2nd page.
<div class="gallery-section">
<div class="container">
<div class="fillter-head">
<div class="row">
<?php
$taxonomy = 'type_cat';
$tax_terms = get_terms($taxonomy, array('hide_empty' => false));
?>
<div class="col-md-8 col-sm-6 col-xs-12">
<ul class="filters" id="filters">
<?php
$count = count($tax_terms);
if ($count > 0) {
?>
<?php
foreach ($tax_terms as $term_single) {
$termname = $term_single->slug;
?>
<li><?php echo $term_single->name; ?></li>
<?php } ?>
<?php } ?>
</ul>
</div>
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="gallery-menu">
<ul>
<?php
$make_taxonomy = 'make_cat';
$tax_makes = get_terms($make_taxonomy, array('hide_empty' => false));
?>
<li>
MAKE
<ul class="gallery-submenu" id="filters">
<?php
$count1 = count($tax_makes);
if ($count1 > 0) {
foreach ($tax_makes as $tax_make) {
$termname_make = $tax_make->slug;
?>
<li><?php echo $tax_make->name; ?></li>
<?php } ?>
<?php } ?>
</ul>
</li>
<?php
$model_taxonomy = 'model_cat';
$tax_models = get_terms($model_taxonomy, array('hide_empty' => false));
?>
<li>MODEL
<ul class="gallery-submenu" id="filters">
<?php
$count_model = count($tax_models);
if ($count_model > 0) {
foreach ($tax_models as $tax_model) {
$termname_model = $tax_model->slug;
?>
<li><?php echo $tax_model->name; ?></li>
<?php } ?>
<?php } ?>
</ul>
</li>
<?php
$wheel_model_taxonomy = 'wheel_model_cat';
$tax_wheel_models = get_terms($wheel_model_taxonomy, array('hide_empty' => false));
?>
<li>WHEEL MODEL
<ul class="gallery-submenu" id="filters">
<?php
$count_wheel_model = count($tax_wheel_models);
if ($count_wheel_model > 0) {
foreach ($tax_wheel_models as $tax_wheel_model) {
$termname_wheel_model = $tax_wheel_model->slug;
?>
<li><?php echo $tax_wheel_model->name; ?></li>
<?php } ?>
<?php } ?>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
<?php
// Get a list of categories
$paged = ( get_query_var('paged') ) ? absint(get_query_var('paged')) : 1;
$args = array(
'post_type' => 'post_gallery',
'posts_per_page' => 9,
'order_by' => 'date',
'order' => 'ASC',
// 'paged' => $paged,
);
$new_query = new WP_Query($args);
// print_r($new_query);
?>
<div id="gallery" class="gallery">
<?php
if ($new_query->have_posts()) :
while ($new_query->have_posts()) : $new_query->the_post();
$terms = get_the_terms($new_query->ID, 'type_cat');
$terms_makes = get_the_terms($new_query->ID, 'make_cat');
$terms_models = get_the_terms($new_query->ID, 'model_cat');
$terms_wheel_models = get_the_terms($new_query->ID, 'wheel_model_cat');
$gallery_videos = get_field('gallery_videos');
$gallery_poster_images = get_field('gallery_poster_images');
?>
<!-- gallery item -->
<div class="item columns4 scale-anm <?php
if ($terms || $terms_makes || $terms_models || $terms_wheel_models):
foreach ($terms as $term) {
echo $term->slug;
}
foreach ($terms_makes as $terms_make) {
echo ' ' . $terms_make->slug;
}
foreach ($terms_models as $terms_model) {
echo ' ' . $terms_model->slug;
}
foreach ($terms_wheel_models as $terms_wheel_model) {
echo ' ' . $terms_wheel_model->slug;
}
endif;
?>">
<?php if ($gallery_videos): ?>
<div class="item-wrap">
<img src="<?php echo $gallery_poster_images; ?>" data-video="<?php echo $gallery_videos; ?>" class="videoPoster">
</div>
<?php else: ?>
<div class="item-wrap">
<a href="<?php echo get_permalink(get_the_ID()); ?>">
<?php the_post_thumbnail('gallery-page-img'); ?>
</a>
<div class="image_links hover-title"><?php the_title(); ?></div>
<!--<div class="image_links hover-title">2016 Dodge Charger Hellcat ‘Plum Loca’ – FR5 Matte Graphite</div>-->
</div>
<?php endif; ?>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
<?php endif; ?>
<!-- close gallery item -->
</div>
<!-- <div class="gallery-pagination">
<ul class="pagination">-->
<?php if (function_exists("pagination")) { ?>
<?php pagination($new_query->max_num_pages); ?>
<?php } ?>
<!-- </ul>
</div>-->
</div>
</div>
This is my PHP code and that is working fine but my filter is not working properly.
Please any suggestion for that.
Also, I'm using ajax through pagination but i don't know its not working.
Please any-one help me about that.

Script stops working after load more function is initiated

I'm working on a wordpress site http://taste.fourseasons.com/ingredients/
At the bottom of the main content section, there's an option to call more posts, but once they are called, the script that allows users to vote on them is not enabled on the new posts. If the vote up button is clicked, the user is brought to the top of the page as if it has an <"a href="#">
I assume that the voting script is getting initiated on load, and but not triggering the voting button on posts that are loaded after the original document is loaded?
Any thoughts?
thanks!
Okay, so here's what I think is the relative code. I tried to set up a jsfiddle, but I think it's all still alittle over my head at the moment. From what I have gathered, I need to create a call back function so that once the new posts are added to the DOM, the original voting script gets reloaded. Hope that makes sense and thanks for taking the time with an aspiring scriptor!
From function.php:
add_action("wp_ajax_add_votes_options", "add_votes_options");
add_action("wp_ajax_nopriv_add_votes_options", "add_votes_options");
function add_votes_options() {
$postid = $_POST['postid'];
$ip = $_POST['ip'];
if (!wp_verify_nonce($_POST['nonce'], 'voting_nonce_'.$postid))
return;
$voter_ips = get_post_meta($postid, "voter_ips", true);
if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
echo "null";
die(0);
} else {
$voter_ips[] = $ip;
update_post_meta($postid, "voter_ips", $voter_ips);
}
$current_votes = get_post_meta($postid, "votes", true);
$new_votes = intval($current_votes) + 1;
update_post_meta($postid, "votes", $new_votes);
$return = $new_votes>1 ? $new_votes : $new_votes;
echo $return;
die(0);
}
And here's how it's being pulled into onto the page:
<div class="grid_row_1">
<div class="grid_col">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php endif; ?>
</div>
<div class="clear"></div>
</div>
<div class="grid_row_1">
<div class="grid_col ingredients post-holder" data-direction="DESC" data-
order="date">
<?php $count = 0; ?>
<?php if (have_posts()) : ?>
<?php query_posts('posts_per_page=15&post_type=ingredient&paged='.$paged);
while ( have_posts() ) : the_post(); ?>
<?php
foreach($ingredient_images as $meta_box) {
$data = get_post_meta($post->ID, 'ingredient-images', true);
switch($meta_box['name']){
case 'ingredient_thumb': $feature_thumb = $data[ $meta_box[ 'name' ]
]; break;
case 'ingredient_status': $feature_thumb_show = $data[ $meta_box[
'name' ] ]; break;
}
}
switch($feature_thumb_show){
case 1: $type='suggested'; break;
case 2: $type='accepted'; break;
case 3: $type='featured'; break;
}
$theDate= get_the_date( 'o-n-j' );
$time = strtotime($theDate);
$one_week_ago = strtotime('-1 week');
switch($count){
case 0: echo '<div class="post one-quarter-sub-col-above-480 one-half-sub-col-at-480 first '.$type.'">'; $count++; break;
case 1: echo '<div class="post one-quarter-sub-col-above-480 one-half-sub-col-at-480 last-at-480 '.$type.'">'; $count++; break;
case 2: echo '<div class="post one-quarter-sub-col-above-480 one-half-sub-col-at-480 first-at-480 '.$type.'">'; $count++; break;
case 3: echo '<div class="post one-quarter-sub-col-above-480 one-half-sub-col-at-480 last '.$type.'">'; $count = 0; break;
}
$votes = get_post_meta($post->ID, "votes", true);
$votes = !empty($votes) ? $votes : "0";
$hasvoted = $_COOKIE['better_votes_'.$post->ID];
$hasvoted = explode(",", $hasvoted);
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = 'unvote-sm';
} else {
$ip = $_SERVER['REMOTE_ADDR'];
$voter_ips = get_post_meta($post->ID, "voter_ips", true);
if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
$vtext = "VOTED";
$class = 'unvote-sm';
} else {
$vtext = "VOTE";
$class = 'vote-sm';
}
}
?>
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce_'.$post->ID.'', 'voting_nonce_'.$post->ID.''); ?>
<div class="bg-white pad-lr10 pad-t10 border-lightgrey margin-b10">
<div class="photo-wrapper ratio-16-9 text-white">
<?php if($feature_thumb_show!=3): ?>
<img src="<?php bloginfo('template_directory'); ?>/images/blank_landscape.gif">
<div class="image-overlay full-width full-height align-center bg-lightblue">
<table class="layout-vert-center full-width full-height">
<tr><td><a class="header font-30 tk3 leading-tight" href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></td></tr>
</table>
</div>
<?php else: ?>
<img src="<?php bloginfo('template_directory'); ?>/includes/timthumb.php?src=<?php echo $feature_thumb; ?>&w=220&h=130&a=t">
<div class="image-overlay bottom bg-black bg-opaque-50 pad-5">
<a class="header font-30 tk3 leading-tight" href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</div>
<?php endif; ?>
<?php if( $time > $one_week_ago ) {?>
<div class="image-overlay"><img src="<?php bloginfo('template_directory'); ?>/images/icon_new.png"></div>
<?php } ?>
</div>
<div class="clear"></div>
<div class="font-16 leading-medium">
<div class="one-half">
<a href="#" class="vote icon-text-link disp-block border-right-lightgrey pad-tb5 pad-r5 tk3" data-post="<?php echo $post->ID ?>">
<div class="vote-text pad-t5 float-left"><?php echo $vtext; ?></div>
<div class="float-right">
<div class="vote-count float-left text-medgrey pad-t5"><?php echo $votes; ?></div>
<span class="icon-holder float-left <?php echo $class; ?>"></span>
</div>
<div class="clear"></div>
</a>
</div>
<div class="one-half">
<a href="#" class="icon-text-link disp-block pad-tb5 pad-l5 tk3">
<div class="pad-t5 float-left hide-at-768">COMMENT</div>
<div class="float-right"><div class="float-left text-medgrey pad-t5"></div><span class="icon-holder comment-sm float-left pad-t5"><?php comments_number( '0', '1', '%' ); ?></span></div>
<div class="clear"></div>
</a>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<?php endwhile;?>
<?php wp_reset_query(); ?>
<?php endif; ?>
Then the new posts get added with:
<div class="grid_row_1">
<div class="grid_col">
<div class="border-top-black margin-tb20">
<div class="align-center"><a class="action-btn pad-lr50 tk3 view-more" href="#">SHOW MORE</a></div>
</div>
</div>
</div>
Thanks again for any insight!

Categories

Resources