jquery datatables scroll to top when pages clicked from bottom - datatables

I am using a jQuery datatable with bottom pagination. When the pages are clicked from bottom , I want it to scroll it to top, so users do not have to manually do that for longer pages. I tried using dataTables_scrollBody, but it doesn't work properly
Here is my code:
oTable = $('#tTable').dataTable({
"fnDrawCallback": function(o) {
$('dataTables_scrollBody').scrollTop(0);
}
});
The page scrolls to top only when you click first/last (which I think is default behaviour), but not with every page click.

Update. The original answer was targeting 1.9.x. In dataTables 1.10.x it is much easier :
table.on('page.dt', function() {
$('html, body').animate({
scrollTop: $(".dataTables_wrapper").offset().top
}, 'slow');
});
demo -> http://jsfiddle.net/wq853akd/
Also, if you're using the bootstrap version of datatables, you may notice that when using the fix, the page actually scrolls back down after scrolling to the top. This is because it is focusing on the clicked button as per this datatables.net thread. You can fix this by simply focusing on the table header after the animate call, like so:
table.on('page.dt', function() {
$('html, body').animate({
scrollTop: $(".dataTables_wrapper").offset().top
}, 'slow');
$('thead tr th:first-child').focus().blur();
});
Original Answer
You should target .dataTables_wrapper and attach the event to .paginate_button instead. Here with a nice little animation :
function paginateScroll() {
$('html, body').animate({
scrollTop: $(".dataTables_wrapper").offset().top
}, 100);
console.log('pagination button clicked'); //remove after test
$(".paginate_button").unbind('click', paginateScroll);
$(".paginate_button").bind('click', paginateScroll);
}
paginateScroll();
see fiddle -> http://jsfiddle.net/EjbEJ/

Since Datatables 1.10 there is this page event
https://datatables.net/reference/event/page
So one can use
$('#example_table').on( 'page.dt', function () {
$('html, body').animate({
scrollTop: 0
}, 300);
} );
Demo: https://jsfiddle.net/mcyhqrdx/

This worked out for me.
$(document).ready(function() {
var oldStart = 0;
$('#example').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fnDrawCallback": function (o) {
if ( o._iDisplayStart != oldStart ) {
var targetOffset = $('#example').offset().top;
$('html,body').animate({scrollTop: targetOffset}, 500);
oldStart = o._iDisplayStart;
}
}
});
} );

I'm also using datatables and Allan's solution (found here) worked perfectly for me.
$(document).ready(function() {
var oldStart = 0;
$('#example').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fnDrawCallback": function (o) {
if ( o._iDisplayStart != oldStart ) {
var targetOffset = $('#example').offset().top;
$('html,body').animate({scrollTop: targetOffset}, 500);
oldStart = o._iDisplayStart;
}
}
});
} );

Thank's from davidkonrad. But when I used his code, after I clicked on paginate button, scroll of page went to top and then after load data, scroll backed to bottom.
I combined multiple posts in StackOverFlow and Datatables forum.
I defined a global variable :
var isScroll = false
When it's clicked on paginate button isScroll set to true:
$(document).on('click', '.paginate_button:not(.disabled)', function () {
isScroll = true;
});
And finally:
$(document).ready(function () {
$('#myDataTable').DataTable({
...
"fnDrawCallback": function () {
if (isScroll) {
$('html, body').animate({
scrollTop: $(".dataTables_wrapper").offset().top
}, 500);
isScroll = false;
}
},
...
});
});
Thanks from #0110

None of the above answers worked for me. Here's my solution.
$("#divContainingTheDataTable").click(function(event){
if ($(event.target).hasClass("paginate_button")) {
$('html, body').animate({
scrollTop: $("#divContainingTheDataTable").offset().top
}, 200);
}
});
I tried targetting .paginate_button but it never seemed to fire. My approach checks the div containing the datatable, if you click on the pagination buttons, the page scrolls up to the top of the container.

For those using the bootstrap version of Datatables:
You may notice that when using the fix from the accepted answer above, the page actually scrolls back down to the paging controls after scrolling to the top. This is because it is focusing on the clicked paging button as per this datatables.net thread. You can fix this by simply focusing on the table header after the animate call like so:
table.on('page.dt', function() {
$('html, body').animate({
scrollTop: $(".dataTables_wrapper").offset().top
}, 'slow');
$('thead tr th:first-child').focus().blur();
});
Note: the chained blur()'ing is done so that you the user doesn't see any focused styles on th:first-child.

Related

Codemirror does not refresh the contents of the textarea until its clicked or if I use the JSON.parse on the contents while setting

I am developing a web application using Vuejs/Nuxtjs within that I have some textarea which is controlled by CodeMirror for beautification purposes. The problem I am facing is that when the content of the CodeMirror changes then it is not reflected on the CodeMirror textarea unless I click on it or if I use the JSON.parse while setting the value in Watch. If I click on it then it reflects the changes and everything is correctly working.
Following is the textarea which is governed by CodeMirror:
<textarea
ref="input"
:value="$store.state.modules.MyModules.input"
class="form-control"
placeholder="Input"
spellcheck="false"
data-gramm="false"
/>
Following is the code sample where I am loading the contents to CodeMirror if the values changes using the Vuejs Watch function:
data () {
return {
inputEditor: null
}
},
watch: {
'$store.state.modules.MyModules.input' (value) {
if (value !== this.inputEditor.getValue()) {
this.inputEditor.setValue(value)
}
}
},
mounted () {
this.inputEditor = CodeMirror.fromTextArea(this.$refs.testInput, {
mode: "applicaton/ld+json",
beautify: { initialBeautify: true, autoBeautify: true },
lineNumbers: true,
indentWithTabs: true,
autofocus: true,
tabSize: 2,
gutters: ["CodeMirror-lint-markers"],
autoCloseBrackets: true,
autoCloseTags: true,
styleActiveLine: true,
styleActiveSelected: true,
autoRefresh: true,
});
// On change of input call the function
this.inputEditor.on("change", this.createTestData);
// Set the height for the input CodeMirror
this.inputEditor.setSize(null, "75vh");
// Add the border for all the CodeMirror textarea
for (const s of document.getElementsByClassName("CodeMirror")) {
s.style.border = "1px solid black";
}
}
I found issues similar to this and tried the following things but still no luck:
Trying to refresh the contents within the watch method:
watch: {
'$store.state.modules.MyModules.input' (value) {
const vm = this
if (value !== this.inputEditor.getValue()) {
this.inputEditor.setValue(value)
setTimeout(function () {
vm.inputEditor.refresh()
}, 1)
}
}
},
Trying to use the autorefresh within my CodeMirror but that also did not work.
What worked for me is that when setting the value I need to use the JSON.parse within the watch method. If I do that then It's working correctly but I do not want to do that:
watch: {
'$store.state.modules.MyModules.input' (value) {
const vm = this
if (value !== this.inputEditor.getValue()) {
this.inputEditor.setValue(JSON.parse(value))
}
}
},
Can someone please inform me why the CodeMirror data will not be updated if I do not do JSON.parse?
Chain this to the master codemirror object, make sure nothing else is chained:
.on('change', editor => {
globalContent = editor.getValue();
});;
Providing the answer as it can be helpful to someone else in the future:
Actually the vm.inputEditor.refresh() will work only problem was that I was using it with setTimeout 0.001s which is way to quick for to refresh.
After trying a lot I found my stupid mistake. I tried to change it to 1000 or 500 and it works now.
Following is the change:
setTimeout(function () {
vm.inputEditor.refresh()
}, 1000)

Pause/Play video in Slick slider

I have a Slick slider with some images and some html5 videos.
I have managed to make the Prev/Next arrows work: if I click on the arrows the slider goes to the next video (it plays automatically) and the previous one is paused.
Now I've added a button to pause/play the current video, but I can't find a way to make it work properly. The button works only the first time a video is played. If I change slide and go back to the same video I am not able to pause it anymore.
$('.sliderVideo').slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: true,
fade: true,
dots: true,
autoplay: true,
autoplaySpeed: 1000,
adaptiveHeight: true,
pauseOnHover:false,
cssEase: 'linear'});
$('.sliderVideo').on('beforeChange', function(event, slick, currentSlide, nextSlide){
$("video").each(function(){
$(this).get(0).pause();
});
});
$('.sliderVideo').on('afterChange', function(event, slick, currentSlide) {
var vid = $(slick.$slides[currentSlide]).find('video');
if (vid.length > 0) {
$('.sliderVideo').slick('slickPause');
$(vid).get(0).play();
var MyPlayButton = $(slick.$slides[currentSlide]).find('.play-button');
//var MyPlayButton = $('.play-button');
MyPlayButton.on('click', function () {
if ($(vid).get(0).paused) {
$(vid).get(0).play();
console.log('play');
} else {
$(vid).get(0).pause();
console.log('paused');
}
return false;
});
}
});
$('video').on('ended',function(){
$('.sliderVideo').slick('slickPlay');});
I would really appreciate your help.
I've created a fiddle https://jsfiddle.net/8ds3Lrxm/22/
OK, fixed this way:
var MyPlayButton = null;
$('.sliderVideo').on('beforeChange', function(event, slick, currentSlide, nextSlide){
if (null !== MyPlayButton) {
MyPlayButton.off('click');
}
$("video").each(function(){
$(this).get(0).pause();
});
});
A very simple way (keeping it simple is best)
this way we reset the video whenever we start playing it...
$('#slider_id').on('beforeChange', function(event, slick, currentSlide, nextSlide){
// pause old video (better performance)
var old_vid = $('#slider_id .slide:eq('+currentSlide+')').find('video');
$(old_vid).get(0).pause();
// play current video from start
var cur_vid = $('#slider_id .slide:eq('+nextSlide+')').find('video');
$(cur_vid).get(0).currentTime = 0;
$(cur_vid).get(0).play();
});
$('.video_banner_slider').on('beforeChange', function(event, slick, currentSlide, nextSlide){
console.log(currentSlide);
$("video").each(function(){
$(this).get(0).pause();
});
});

how to make browser back close magnific-popup

I have the popup working but sometimes a user clicks the back button on their browser to close the popup.
How can I make the browser back button close a 'magnific-popup' that is already open?
Thanks
After some digging found history.js and then the following
var magnificPopup = null;
jQuery(document).ready(function ($) {
var $img = $(".img-link");
if ($img.length) {
$img.magnificPopup({
type: 'image',
preloader: true,
closeOnContentClick: true,
enableEscapeKey: false,
showCloseBtn: true,
removalDelay: 100,
mainClass: 'mfp-fade',
tClose: '',
callbacks: {
open: function () {
History.Adapter.bind(window, 'statechange', closePopup);
History.pushState({ url: document.location.href }, document.title, "?large");
$(window).on('resize', closePopup);
magnificPopup = this;
},
close: function () {
$(window).unbind('statechange', closePopup)
.off('resize', closePopup);
var State = History.getState();
History.replaceState(null, document.title, State.data["url"]);
magnificPopup = null;
}
}
});
}
});
function closePopup () {
if (magnificPopup != null)
magnificPopup.close();
}
I'm using this solution:
callbacks: {
open: function() {
location.href = location.href.split('#')[0] + "#gal";
}
,close: function() {
if (location.hash) history.go(-1);
}
}
And this code:
$(window).on('hashchange',function() {
if(location.href.indexOf("#gal")<0) {
$.magnificPopup.close();
}
});
So, on gallery open I add #gal hash. When user closes I virtually click back button to remove it. If user clicks back button - everything works fine olso.
This solution does not break back button behavior and does no require any additional plugins.
Comments are welcome.
Just to add to your answer, these are the meaningful lines that I got to work for me.
callbacks:
open: ->
History.pushState({ url: document.location.href }, null, "?dialogOpen")
History.Adapter.bind(window, 'statechange', attemptToCloseDialog)
close: ->
$(window).unbind('statechange', attemptToCloseDialog)
History.replaceState(null, null, History.getState().data['url'])
With attempt being:
attemptToCloseDialog = ->
$.magnificPopup.close() if $.magnificPopup.instance

Non closable dialogbox from Extension Library

I'm creating a dialogbox from ExtLib and I want to prevent users to press Escape or click on X icon.
I've checked several posts about same implementation but none of them using a Dialogbox from ExtLib.
I was able to hide icon with CSS and I'm trying with dojo.connect to prevent the use of Escape key:
XSP.addOnLoad(function(){
dojo.connect(dojo.byId("#{id:dlgMsg}"), "onkeypress", function (evt) {
if(evt.keyCode == dojo.keys.ESCAPE) {
dojo.stopEvent(evt);
}
});
});
Note I'm able to get it working only if I create my dialogbox manually and not from ExtLib; then I can use for example:
dojo.connect(dojo.byId("divDlgLock"), "onkeypress", function (evt) {
if(evt.keyCode == dojo.keys.ESCAPE) {
dojo.stopEvent(evt);
}
});
Any ideas?
By adding an output script block you can extend the existing declaration:
<xp:scriptBlock id="scriptBlockNonCloseableDialog">
<xp:this.value>
<![CDATA[
dojo.provide("extlib.dijit.OneUIDialogNonCloseableDialog");
dojo.require("extlib.dijit.Dialog");
dojo.declare(
"extlib.dijit.OneUIDialogNonCloseableDialog",
extlib.dijit.Dialog,
{
baseClass: "",
templateString: dojo.cache("extlib.dijit", "templates/OneUIDialog.html"),
disableCloseButton: true,
_onKey: function(evt){
if(this.disableCloseButton &&
evt.charOrCode == dojo.keys.ESCAPE) return;
this.inherited(arguments);
},
_updateCloseButtonState: function(){
dojo.style(this.closeButtonNode,
"display",this.disableCloseButton ? "none" : "block");
},
postCreate: function(){
this.inherited(arguments);
this._updateCloseButtonState();
dojo.query('form', dojo.body())[0].appendChild(this.domNode);
},
_setup: function() {
this.inherited(arguments);
if (this.domNode.parentNode.nodeName.toLowerCase() == 'body')
dojo.query('form', dojo.body())[0].appendChild(this.domNode);
}
}
);
// This is used by the picker dialog to grab the correct UI
XSP._dialog_type="extlib.dijit.OneUIDialogNonCloseableDialog";
]]>
</xp:this.value>
</xp:scriptBlock>

Header and Footer keep showing up with modal pop up window

I just want to show basic HTML without the header and footer of my main page when using a modal window.
How can one do that in MVC3/4?
Here is an example of what is happening...
Not sure why it is doing that.
This is a basic jquery modal window call
$(function () {
//$('a.tempDlg').live("click", function (event) { loadDialog(this, event, '#edit-set'); });
//$('a.AddPatDlg').live("click", function(event) {loadDialog(this, event, '#addPat');});
//debugger;
$('a.addEncounter').live("click", function (event) { loadDialog(this, event, '#DisplayUniqueEncounters'); });
$('a.SearchEncounter').live("click", function (event) { loadDialog(this, event, '#searchEncounter'); });
//$("#sID").click(function (event) { loadDialogByClick(this, event, '#searchEncounter'); });
});
function loadDialog(tag, event, target) {
//debugger;
event.preventDefault();
var $loading = $('<img src="<%=Url.Content("~/Images/ajax-loader.gif")%>" alt="loading" class="ui-loading-icon">');
var $url = $(tag).attr('href');
var $title = $(tag).attr('title');
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
, title: $title
, width: 1200
, modal: true
, minHeight: 550
, show: 'fade'
, hide: 'fade'
});
$dialog.dialog('open');
};
I have done this before without including the header and footer, and I forget how it was done? I must be missing a step.
You can also set the Layout = null at the top of the page
That is correct... I want to give nemesv credit for this answer, but he didn't answer the question. So I will just say that he was right. You need to return a partialView(), not just a regular view... Returning a regular view always gets all of the other MVC markup. Thanks...