Ticker-style getting cut in Mobile View - javascript

The requirement is to sow the information continuously hence opted for a ticker style.
Now I am using an [ticker-style.css] along with [jquery.ticker.js]
It works fine in a Full Screen however while browsing in a Mobile/Tabler - the text is getting cut (see below screenshot) - I tried to play around the width however the rendering was not as expected.
Can you help here.
Thanks in advance.
/*
jQuery News Ticker is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
jQuery News Ticker is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with jQuery News Ticker. If not, see <http://www.gnu.org/licenses/>.
*/
(function($){
$.fn.ticker = function(options) {
// Extend our default options with those provided.
// Note that the first arg to extend is an empty object -
// this is to keep from overriding our "defaults" object.
var opts = $.extend({}, $.fn.ticker.defaults, options);
// check that the passed element is actually in the DOM
if ($(this).length == 0) {
if (window.console && window.console.log) {
window.console.log('Element does not exist in DOM!');
}
else {
alert('Element does not exist in DOM!');
}
return false;
}
/* Get the id of the UL to get our news content from */
var newsID = '#' + $(this).attr('id');
/* Get the tag type - we will check this later to makde sure it is a UL tag */
var tagType = $(this).get(0).tagName;
return this.each(function() {
// get a unique id for this ticker
var uniqID = getUniqID();
/* Internal vars */
var settings = {
position: 0,
time: 0,
distance: 0,
newsArr: {},
play: true,
paused: false,
contentLoaded: false,
dom: {
contentID: '#ticker-content-' + uniqID,
titleID: '#ticker-title-' + uniqID,
titleElem: '#ticker-title-' + uniqID + ' SPAN',
tickerID : '#ticker-' + uniqID,
wrapperID: '#ticker-wrapper-' + uniqID,
revealID: '#ticker-swipe-' + uniqID,
revealElem: '#ticker-swipe-' + uniqID + ' SPAN',
controlsID: '#ticker-controls-' + uniqID,
prevID: '#prev-' + uniqID,
nextID: '#next-' + uniqID,
playPauseID: '#play-pause-' + uniqID
}
};
// if we are not using a UL, display an error message and stop any further execution
if (tagType != 'UL' && tagType != 'OL' && opts.htmlFeed === true) {
debugError('Cannot use <' + tagType.toLowerCase() + '> type of element for this plugin - must of type <ul> or <ol>');
return false;
}
// set the ticker direction
opts.direction == 'rtl' ? opts.direction = 'right' : opts.direction = 'left';
// lets go...
initialisePage();
/* Function to get the size of an Object*/
function countSize(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function getUniqID() {
var newDate = new Date;
return newDate.getTime();
}
/* Function for handling debug and error messages */
function debugError(obj) {
if (opts.debugMode) {
if (window.console && window.console.log) {
window.console.log(obj);
}
else {
alert(obj);
}
}
}
/* Function to setup the page */
function initialisePage() {
// process the content for this ticker
processContent();
// add our HTML structure for the ticker to the DOM
$(newsID).wrap('<div id="' + settings.dom.wrapperID.replace('#', '') + '"></div>');
// remove any current content inside this ticker
$(settings.dom.wrapperID).children().remove();
$(settings.dom.wrapperID).append('<div id="' + settings.dom.tickerID.replace('#', '') + '" class="ticker"><div id="' + settings.dom.titleID.replace('#', '') + '" class="ticker-title"><span><!-- --></span></div><p id="' + settings.dom.contentID.replace('#', '') + '" class="ticker-content"></p><div id="' + settings.dom.revealID.replace('#', '') + '" class="ticker-swipe"><span><!-- --></span></div></div>');
$(settings.dom.wrapperID).removeClass('no-js').addClass('ticker-wrapper has-js ' + opts.direction);
// hide the ticker
$(settings.dom.tickerElem + ',' + settings.dom.contentID).hide();
// add the controls to the DOM if required
if (opts.controls) {
// add related events - set functions to run on given event
$(settings.dom.controlsID).on('click mouseover mousedown mouseout mouseup', function (e) {
var button = e.target.id;
if (e.type == 'click') {
switch (button) {
case settings.dom.prevID.replace('#', ''):
// show previous item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('prev');
break;
case settings.dom.nextID.replace('#', ''):
// show next item
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
manualChangeContent('next');
break;
case settings.dom.playPauseID.replace('#', ''):
// play or pause the ticker
if (settings.play == true) {
settings.paused = true;
$(settings.dom.playPauseID).addClass('paused');
pauseTicker();
}
else {
settings.paused = false;
$(settings.dom.playPauseID).removeClass('paused');
restartTicker();
}
break;
}
}
else if (e.type == 'mouseover' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('over');
}
else if (e.type == 'mousedown' && $('#' + button).hasClass('controls')) {
$('#' + button).addClass('down');
}
else if (e.type == 'mouseup' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('down');
}
else if (e.type == 'mouseout' && $('#' + button).hasClass('controls')) {
$('#' + button).removeClass('over');
}
});
// add controls HTML to DOM
$(settings.dom.wrapperID).append('<ul id="' + settings.dom.controlsID.replace('#', '') + '" class="ticker-controls"><li id="' + settings.dom.playPauseID.replace('#', '') + '" class="jnt-play-pause controls"><!-- --></li><li id="' + settings.dom.prevID.replace('#', '') + '" class="jnt-prev controls"><!-- --></li><li id="' + settings.dom.nextID.replace('#', '') + '" class="jnt-next controls"><!-- --></li></ul>');
}
if (opts.displayType != 'fade') {
// add mouse over on the content
$(settings.dom.contentID).mouseover(function () {
if (settings.paused == false) {
pauseTicker();
}
}).mouseout(function () {
if (settings.paused == false) {
restartTicker();
}
});
}
// we may have to wait for the ajax call to finish here
if (!opts.ajaxFeed) {
setupContentAndTriggerDisplay();
}
}
/* Start to process the content for this ticker */
function processContent() {
// check to see if we need to load content
if (settings.contentLoaded == false) {
// construct content
if (opts.ajaxFeed) {
if (opts.feedType == 'xml') {
$.ajax({
url: opts.feedUrl,
cache: false,
dataType: opts.feedType,
async: true,
success: function(data){
count = 0;
// get the 'root' node
for (var a = 0; a < data.childNodes.length; a++) {
if (data.childNodes[a].nodeName == 'rss') {
xmlContent = data.childNodes[a];
}
}
// find the channel node
for (var i = 0; i < xmlContent.childNodes.length; i++) {
if (xmlContent.childNodes[i].nodeName == 'channel') {
xmlChannel = xmlContent.childNodes[i];
}
}
// for each item create a link and add the article title as the link text
for (var x = 0; x < xmlChannel.childNodes.length; x++) {
if (xmlChannel.childNodes[x].nodeName == 'item') {
xmlItems = xmlChannel.childNodes[x];
var title, link = false;
for (var y = 0; y < xmlItems.childNodes.length; y++) {
if (xmlItems.childNodes[y].nodeName == 'title') {
title = xmlItems.childNodes[y].lastChild.nodeValue;
}
else if (xmlItems.childNodes[y].nodeName == 'link') {
link = xmlItems.childNodes[y].lastChild.nodeValue;
}
if ((title !== false && title != '') && link !== false) {
settings.newsArr['item-' + count] = { type: opts.titleText, content: '' + title + '' }; count++; title = false; link = false;
}
}
}
}
// quick check here to see if we actually have any content - log error if not
if (countSize(settings.newsArr < 1)) {
debugError('Couldn\'t find any content from the XML feed for the ticker to use!');
return false;
}
settings.contentLoaded = true;
setupContentAndTriggerDisplay();
}
});
}
else {
debugError('Code Me!');
}
}
else if (opts.htmlFeed) {
if($(newsID + ' LI').length > 0) {
$(newsID + ' LI').each(function (i) {
// maybe this could be one whole object and not an array of objects?
settings.newsArr['item-' + i] = { type: opts.titleText, content: $(this).html()};
});
}
else {
debugError('Couldn\'t find HTML any content for the ticker to use!');
return false;
}
}
else {
debugError('The ticker is set to not use any types of content! Check the settings for the ticker.');
return false;
}
}
}
function setupContentAndTriggerDisplay() {
settings.contentLoaded = true;
// update the ticker content with the correct item
// insert news content into DOM
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
// get the values of content and set the time of the reveal (so all reveals have the same speed regardless of content size)
distance = $(settings.dom.contentID).width();
time = distance / opts.speed;
// start the ticker animation
revealContent();
}
// slide back cover or fade in content
function revealContent() {
$(settings.dom.contentID).css('opacity', '1');
if(settings.play) {
// get the width of the title element to offset the content and reveal
var offset = $(settings.dom.titleID).width() + 20;
$(settings.dom.revealID).css(opts.direction, offset + 'px');
// show the reveal element and start the animation
if (opts.displayType == 'fade') {
// fade in effect ticker
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').fadeIn(opts.fadeInSpeed, postReveal);
});
}
else if (opts.displayType == 'scroll') {
// to code
}
else {
// default bbc scroll effect
$(settings.dom.revealElem).show(0, function () {
$(settings.dom.contentID).css(opts.direction, offset + 'px').show();
// set our animation direction
animationAction = opts.direction == 'right' ? { marginRight: distance + 'px'} : { marginLeft: distance + 'px' };
$(settings.dom.revealID).css('margin-' + opts.direction, '0px').delay(20).animate(animationAction, time, 'linear', postReveal);
});
}
}
else {
return false;
}
};
// here we hide the current content and reset the ticker elements to a default state ready for the next ticker item
function postReveal() {
if(settings.play) {
// we have to separately fade the content out here to get around an IE bug - needs further investigation
$(settings.dom.contentID).delay(opts.pauseOnItems).fadeOut(opts.fadeOutSpeed);
// deal with the rest of the content, prepare the DOM and trigger the next ticker
if (opts.displayType == 'fade') {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
}
else {
$(settings.dom.revealID).hide(0, function () {
$(settings.dom.contentID).fadeOut(opts.fadeOutSpeed, function () {
$(settings.dom.wrapperID)
.find(settings.dom.revealElem + ',' + settings.dom.contentID)
.hide()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.show()
.end().find(settings.dom.tickerID + ',' + settings.dom.revealID)
.removeAttr('style');
setupContentAndTriggerDisplay();
});
});
}
}
else {
$(settings.dom.revealElem).hide();
}
}
// pause ticker
function pauseTicker() {
settings.play = false;
// stop animation and show content - must pass "true, true" to the stop function, or we can get some funky behaviour
$(settings.dom.tickerID + ',' + settings.dom.revealID + ',' + settings.dom.titleID + ',' + settings.dom.titleElem + ',' + settings.dom.revealElem + ',' + settings.dom.contentID).stop(true, true);
$(settings.dom.revealID + ',' + settings.dom.revealElem).hide();
$(settings.dom.wrapperID)
.find(settings.dom.titleID + ',' + settings.dom.titleElem).show()
.end().find(settings.dom.contentID).show();
}
// play ticker
function restartTicker() {
settings.play = true;
settings.paused = false;
// start the ticker again
postReveal();
}
// change the content on user input
function manualChangeContent(direction) {
pauseTicker();
switch (direction) {
case 'prev':
if (settings.position == 0) {
settings.position = countSize(settings.newsArr) -2;
}
else if (settings.position == 1) {
settings.position = countSize(settings.newsArr) -1;
}
else {
settings.position = settings.position - 2;
}
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
case 'next':
$(settings.dom.titleElem).html(settings.newsArr['item-' + settings.position].type);
$(settings.dom.contentID).html(settings.newsArr['item-' + settings.position].content);
break;
}
// set the next content item to be used - loop round if we are at the end of the content
if (settings.position == (countSize(settings.newsArr) -1)) {
settings.position = 0;
}
else {
settings.position++;
}
}
});
};
// plugin defaults - added as a property on our plugin function
$.fn.ticker.defaults = {
speed: 0.10,
ajaxFeed: false,
feedUrl: '',
feedType: 'xml',
displayType: 'reveal',
htmlFeed: true,
debugMode: true,
controls: true,
titleText: '',
direction: 'ltr',
pauseOnItems: 3000,
fadeInSpeed: 600,
fadeOutSpeed: 300
};
})(jQuery);
/* Ticker Styling */
.ticker-wrapper.has-js {
margin: 0;
padding: 0;
width: 780px;
height: 32px;
display: block;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
background-color:inherit;
font-size: inherit;
}
.ticker {
width: 710px;
height: 23px;
display: block;
position: relative;
overflow: hidden;
background-color: #fff;
#media #{$xs}{
width: 200px;
}
}
.ticker-title {
padding-top: 9px;
color: #990000;
font-weight: bold;
background-color: #fff;
text-transform: capitalize;
}
.ticker-content {
margin: 0px;
/* padding-top: 9px; */
position: absolute;
color: #506172;
font-weight: normal;
background-color: #fff;
overflow: hidden;
white-space: nowrap;
font-family: "Roboto",sans-serif;
font-size: 16px;
}
.ticker-content:focus {
none;
}
.ticker-content a {
text-decoration: none;
color: #1F527B;
}
.ticker-content a:hover {
text-decoration: underline;
color: #0D3059;
}
.ticker-swipe {
padding-top: 9px;
position: absolute;
top: 0px;
background-color: #fff;
display: block;
width: 800px;
height: 23px;
}
.ticker-swipe span {
margin-left: 1px;
background-color: #fff;
border-bottom: 1px solid #1F527B;
height: 12px;
width: 7px;
display: block;
}
.ticker-controls {
padding: 8px 0px 0px 0px;
list-style-type: none;
float: left;
}
.ticker-controls li {
padding: 0px;
margin-left: 5px;
float: left;
cursor: pointer;
height: 16px;
width: 16px;
display: block;
}
.ticker-controls li.jnt-play-pause {
background-image: url('../images/controls.png');
background-position: 32px 16px;
}
.ticker-controls li.jnt-play-pause.over {
background-position: 32px 32px;
}
.ticker-controls li.jnt-play-pause.down {
background-position: 32px 0px;
}
.ticker-controls li.jnt-play-pause.paused {
background-image: url('../images/controls.png');
background-position: 48px 16px;
}
.ticker-controls li.jnt-play-pause.paused.over {
background-position: 48px 32px;
}
.ticker-controls li.jnt-play-pause.paused.down {
background-position: 48px 0px;
}
.ticker-controls li.jnt-prev {
background-image: url('../images/controls.png');
background-position: 0px 16px;
}
.ticker-controls li.jnt-prev.over {
background-position: 0px 32px;
}
.ticker-controls li.jnt-prev.down {
background-position: 0px 0px;
}
.ticker-controls li.jnt-next {
background-image: url('../images/controls.png');
background-position: 16px 16px;
}
.ticker-controls li.jnt-next.over {
background-position: 16px 32px;
}
.ticker-controls li.jnt-next.down {
background-position: 16px 0px;
}
.js-hidden {
display: none;
}
.no-js-news {
padding: 10px 0px 0px 45px;
color: #fff;
}
.left .ticker-swipe {
/*left: 80px;*/
}
.left .ticker-controls, .left .ticker-content, .left .ticker-title, .left .ticker {
float: left;
}
.left .ticker-controls {
padding-left: 6px;
}
.right .ticker-swipe {
/*right: 80px;*/
}
.right .ticker-controls, .right .ticker-content, .right .ticker-title, .right .ticker {
float: right;
}
.right .ticker-controls {
padding-right: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Trending now</strong>
<!-- <p>Rem ipsum dolor sit amet, consectetur adipisicing elit.</p> -->
<div class="trending-animated">
<ul id="js-news" class="js-hidden">
<li class="news-item">Dolor sit amet, consectetur adipisicing elit.</li>
<li class="news-item">Spondon IT sit amet, consectetur.......</li>
<li class="news-item">Rem ipsum dolor sit amet, consectetur adipisicing elit.</li>
</ul>
</div>

The problem is that you are setting fixed widths for ticker elements.The ticker container has a width of 720px no matter what size the screen, and on screens < 767px the container for the scrolling text is just 230px.
Either change the CSS if it is your own, or if not you can add these rules after the Ticker CSS in included:
#media (max-width: 767px){
.ticker-wrapper.has-js,
.ticker,
.trending-tittle .ticker {
width: 100%!important;
}
}
This sets them to use the full width of the screen.

Related

Disable multiple checkboxes in dropdowns based on another selected checkbox of a first dropdown

Disable multiple checkboxes in dropdowns based on another selected checkbox of a first dropdown
I have multi-select 3 drop downs. All three dropdowns have same values. I want to disable second and third drop-down values based on the selected value of first. That means, when the user selected two options in first drop-down, the checkbox which contains those selected values in the first drop-down should get disabled in second drop-down and third drop-down and when user selected three options in second drop-down, the checkbox which contains those selected values in first drop-down, as well as second drop-down, should get disabled in third drop-down.
Priority is First drop-down than second and third respectively.
(function($) {
$.fn.fSelect = function(options) {
if ('string' === typeof options) {
var settings = options;
} else {
var settings = $.extend({
placeholder: 'Select some options',
numDisplayed: 3,
overflowText: '{n} selected',
searchText: 'Search',
showSearch: true,
optionFormatter: false
}, options);
}
/**
* Constructor
*/
function fSelect(select, settings) {
this.$select = $(select);
this.settings = settings;
this.create();
}
/**
* Prototype class
*/
fSelect.prototype = {
create: function() {
this.settings.multiple = this.$select.is('[multiple]');
var multiple = this.settings.multiple ? ' multiple' : '';
this.$select.wrap('<div class="fs-wrap' + multiple + '" tabindex="0" />');
this.$select.before('<div class="fs-label-wrap"><div class="fs-label">' + this.settings.placeholder + '</div><span class="fs-arrow"></span></div>');
this.$select.before('<div class="fs-dropdown hidden"><div class="fs-options"></div></div>');
this.$select.addClass('hidden');
this.$wrap = this.$select.closest('.fs-wrap');
this.$wrap.data('id', window.fSelect.num_items);
window.fSelect.num_items++;
this.reload();
},
reload: function() {
if (this.settings.showSearch) {
var search = '<div class="fs-search"><input type="search" placeholder="' + this.settings.searchText + '" /></div>';
this.$wrap.find('.fs-dropdown').prepend(search);
}
this.idx = 0;
this.optgroup = 0;
this.selected = [].concat(this.$select.val()); // force an array
var choices = this.buildOptions(this.$select);
this.$wrap.find('.fs-options').html(choices);
this.reloadDropdownLabel();
},
destroy: function() {
this.$wrap.find('.fs-label-wrap').remove();
this.$wrap.find('.fs-dropdown').remove();
this.$select.unwrap().removeClass('hidden');
},
buildOptions: function($element) {
var $this = this;
var choices = '';
$element.children().each(function(i, el) {
var $el = $(el);
if ('optgroup' == $el.prop('nodeName').toLowerCase()) {
choices += '<div class="fs-optgroup-label" data-group="' + $this.optgroup + '">' + $el.prop('label') + '</div>';
choices += $this.buildOptions($el);
$this.optgroup++;
} else {
var val = $el.prop('value');
// exclude the first option in multi-select mode
if (0 < $this.idx || '' != val || !$this.settings.multiple) {
var disabled = $el.is(':disabled') ? ' disabled' : '';
var selected = -1 < $.inArray(val, $this.selected) ? ' selected' : '';
var group = ' g' + $this.optgroup;
var row = '<div class="fs-option' + selected + disabled + group + '" data-value="' + val + '" data-index="' + $this.idx + '"><span class="fs-checkbox"><i></i></span><div class="fs-option-label">' + $el.html() + '</div></div>';
if ('function' === typeof $this.settings.optionFormatter) {
row = $this.settings.optionFormatter(row);
}
choices += row;
$this.idx++;
}
}
});
return choices;
},
reloadDropdownLabel: function() {
var settings = this.settings;
var labelText = [];
this.$wrap.find('.fs-option.selected').each(function(i, el) {
labelText.push($(el).find('.fs-option-label').text());
});
if (labelText.length < 1) {
labelText = settings.placeholder;
} else if (labelText.length > settings.numDisplayed) {
labelText = settings.overflowText.replace('{n}', labelText.length);
} else {
labelText = labelText.join(', ');
}
this.$wrap.find('.fs-label').html(labelText);
this.$wrap.toggleClass('fs-default', labelText === settings.placeholder);
this.$select.change();
}
}
/**
* Loop through each matching element
*/
return this.each(function() {
var data = $(this).data('fSelect');
if (!data) {
data = new fSelect(this, settings);
$(this).data('fSelect', data);
}
if ('string' === typeof settings) {
data[settings]();
}
});
}
/**
* Events
*/
window.fSelect = {
'num_items': 0,
'active_id': null,
'active_el': null,
'last_choice': null,
'idx': -1
};
$(document).on('click', '.fs-option:not(.hidden, .disabled)', function(e) {
var $wrap = $(this).closest('.fs-wrap');
var do_close = false;
if ($wrap.hasClass('multiple')) {
var selected = [];
// shift + click support
if (e.shiftKey && null != window.fSelect.last_choice) {
var current_choice = parseInt($(this).attr('data-index'));
var addOrRemove = !$(this).hasClass('selected');
var min = Math.min(window.fSelect.last_choice, current_choice);
var max = Math.max(window.fSelect.last_choice, current_choice);
for (i = min; i <= max; i++) {
$wrap.find('.fs-option[data-index=' + i + ']')
.not('.hidden, .disabled')
.each(function() {
$(this).toggleClass('selected', addOrRemove);
});
}
} else {
window.fSelect.last_choice = parseInt($(this).attr('data-index'));
$(this).toggleClass('selected');
}
$wrap.find('.fs-option.selected').each(function(i, el) {
selected.push($(el).attr('data-value'));
});
} else {
var selected = $(this).attr('data-value');
$wrap.find('.fs-option').removeClass('selected');
$(this).addClass('selected');
do_close = true;
}
$wrap.find('select').val(selected);
$wrap.find('select').fSelect('reloadDropdownLabel');
// fire an event
$(document).trigger('fs:changed', $wrap);
if (do_close) {
closeDropdown($wrap);
}
});
$(document).on('keyup', '.fs-search input', function(e) {
if (40 == e.which) { // down
$(this).blur();
return;
}
var $wrap = $(this).closest('.fs-wrap');
var matchOperators = /[|\\{}()[\]^$+*?.]/g;
var keywords = $(this).val().replace(matchOperators, '\\$&');
$wrap.find('.fs-option, .fs-optgroup-label').removeClass('hidden');
if ('' != keywords) {
$wrap.find('.fs-option').each(function() {
var regex = new RegExp(keywords, 'gi');
if (null === $(this).find('.fs-option-label').text().match(regex)) {
$(this).addClass('hidden');
}
});
$wrap.find('.fs-optgroup-label').each(function() {
var group = $(this).attr('data-group');
var num_visible = $(this).closest('.fs-options').find('.fs-option.g' + group + ':not(.hidden)').length;
if (num_visible < 1) {
$(this).addClass('hidden');
}
});
}
setIndexes($wrap);
});
$(document).on('click', function(e) {
var $el = $(e.target);
var $wrap = $el.closest('.fs-wrap');
if (0 < $wrap.length) {
// user clicked another fSelect box
if ($wrap.data('id') !== window.fSelect.active_id) {
closeDropdown();
}
// fSelect box was toggled
if ($el.hasClass('fs-label') || $el.hasClass('fs-arrow')) {
var is_hidden = $wrap.find('.fs-dropdown').hasClass('hidden');
if (is_hidden) {
openDropdown($wrap);
} else {
closeDropdown($wrap);
}
}
}
// clicked outside, close all fSelect boxes
else {
closeDropdown();
}
});
$(document).on('keydown', function(e) {
var $wrap = window.fSelect.active_el;
var $target = $(e.target);
// toggle the dropdown on space
if ($target.hasClass('fs-wrap')) {
if (32 == e.which) {
$target.find('.fs-label').trigger('click');
return;
}
}
// preserve spaces during search
else if (0 < $target.closest('.fs-search').length) {
if (32 == e.which) {
return;
}
} else if (null === $wrap) {
return;
}
if (38 == e.which) { // up
e.preventDefault();
$wrap.find('.fs-option.hl').removeClass('hl');
var $current = $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']');
var $prev = $current.prevAll('.fs-option:not(.hidden, .disabled)');
if ($prev.length > 0) {
window.fSelect.idx = parseInt($prev.attr('data-index'));
$wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
setScroll($wrap);
} else {
window.fSelect.idx = -1;
$wrap.find('.fs-search input').focus();
}
} else if (40 == e.which) { // down
e.preventDefault();
var $current = $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']');
if ($current.length < 1) {
var $next = $wrap.find('.fs-option:not(.hidden, .disabled):first');
} else {
var $next = $current.nextAll('.fs-option:not(.hidden, .disabled)');
}
if ($next.length > 0) {
window.fSelect.idx = parseInt($next.attr('data-index'));
$wrap.find('.fs-option.hl').removeClass('hl');
$wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
setScroll($wrap);
}
} else if (32 == e.which || 13 == e.which) { // space, enter
e.preventDefault();
$wrap.find('.fs-option.hl').click();
} else if (27 == e.which) { // esc
closeDropdown($wrap);
}
});
function setIndexes($wrap) {
$wrap.find('.fs-option.hl').removeClass('hl');
$wrap.find('.fs-search input').focus();
window.fSelect.idx = -1;
}
function setScroll($wrap) {
var $container = $wrap.find('.fs-options');
var $selected = $wrap.find('.fs-option.hl');
var itemMin = $selected.offset().top + $container.scrollTop();
var itemMax = itemMin + $selected.outerHeight();
var containerMin = $container.offset().top + $container.scrollTop();
var containerMax = containerMin + $container.outerHeight();
if (itemMax > containerMax) { // scroll down
var to = $container.scrollTop() + itemMax - containerMax;
$container.scrollTop(to);
} else if (itemMin < containerMin) { // scroll up
var to = $container.scrollTop() - containerMin - itemMin;
$container.scrollTop(to);
}
}
function openDropdown($wrap) {
window.fSelect.active_el = $wrap;
window.fSelect.active_id = $wrap.data('id');
window.fSelect.initial_values = $wrap.find('select').val();
$wrap.find('.fs-dropdown').removeClass('hidden');
$wrap.addClass('fs-open');
setIndexes($wrap);
}
function closeDropdown($wrap) {
if ('undefined' == typeof $wrap && null != window.fSelect.active_el) {
$wrap = window.fSelect.active_el;
}
if ('undefined' !== typeof $wrap) {
// only trigger if the values have changed
var initial_values = window.fSelect.initial_values;
var current_values = $wrap.find('select').val();
if (JSON.stringify(initial_values) != JSON.stringify(current_values)) {
$(document).trigger('fs:closed', $wrap);
}
}
$('.fs-wrap').removeClass('fs-open');
$('.fs-dropdown').addClass('hidden');
window.fSelect.active_el = null;
window.fSelect.active_id = null;
window.fSelect.last_choice = null;
}
})(jQuery);
.fs-wrap {
display: inline-block;
cursor: pointer;
line-height: 1;
width: 340px;
}
.fs-label-wrap {
position: relative;
background-color: #fff;
border: 1px solid #ddd;
cursor: default;
}
.fs-label-wrap,
.fs-dropdown {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.fs-label-wrap .fs-label {
padding: 6px 22px 6px 8px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.fs-arrow {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #333;
position: absolute;
top: 0;
right: 5px;
bottom: 0;
margin: auto;
}
.fs-dropdown {
position: absolute;
background-color: #fff;
border: 1px solid #ddd;
width: 340px;
margin-top: 5px;
z-index: 1000;
}
.fs-dropdown .fs-options {
max-height: 200px;
overflow: auto;
}
.fs-search input {
border: none !important;
box-shadow: none !important;
outline: none;
padding: 4px 0;
width: 100%;
}
.fs-option,
.fs-search,
.fs-optgroup-label {
padding: 6px 8px;
border-bottom: 1px solid #eee;
cursor: default;
}
.fs-option:last-child {
border-bottom: none;
}
.fs-search {
padding: 0 4px;
}
.fs-option {
cursor: pointer;
}
.fs-option.disabled {
opacity: 0.4;
cursor: default;
}
.fs-option.hl {
background-color: #f5f5f5;
}
.fs-wrap.multiple .fs-option {
position: relative;
padding-left: 30px;
}
.fs-wrap.multiple .fs-checkbox {
position: absolute;
display: block;
width: 30px;
top: 0;
left: 0;
bottom: 0;
}
.fs-wrap.multiple .fs-option .fs-checkbox i {
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 14px;
height: 14px;
border: 1px solid #aeaeae;
border-radius: 2px;
background-color: #fff;
}
.fs-wrap.multiple .fs-option.selected .fs-checkbox i {
background-color: rgb(17, 169, 17);
border-color: transparent;
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAGCAYAAAD+Bd/7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNXG14zYAAABMSURBVAiZfc0xDkAAFIPhd2Kr1WRjcAExuIgzGUTIZ/AkImjSofnbNBAfHvzAHjOKNzhiQ42IDFXCDivaaxAJd0xYshT3QqBxqnxeHvhunpu23xnmAAAAAElFTkSuQmCC');
background-repeat: no-repeat;
background-position: center;
}
.fs-optgroup-label {
font-weight: bold;
text-align: center;
}
.hidden {
display: none;
}
<html>
<head>
<meta charset="UTF-8">
<title>Create Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script>
<!-- The below url are required for dropdown -->
<link href="http://localhost/Performance/Test/css/fselect.css" rel="stylesheet">
<script src="http://localhost/Performance/Test/js/fSelect.js"></script>
<script>
(function($) {
$(function() {
$('#project_manager').fSelect();
$('#test_engineer').fSelect();
$('#viewer').fSelect();
});
})(jQuery);
</script>
</head>
<body>
<label>Select Project Manager :</label><br/>
<select id="project_manager" name="project_manager[]" multiple="multiple"><br/>
<optgroup label="pm">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</optgroup>
</select><br/>
<label>Select Test Engineer :</label><br/>
<select id="test_engineer" name="test_engineer[]" multiple="multiple"><br/>
<optgroup label="te">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</optgroup>
</select><br/>
<label>Select Viewer :</label><br/>
<select id="viewer" name="viewer[]" multiple="multiple"><br/>
<optgroup label="viewer">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</optgroup>
</select><br/>
</body>
</html>

javascript - mimik window.confirm with keeping boolean returns

I'm trying to implement my own confirmation box in JavaScript. But I don't want to change all the places where I have used window.confirm. So, I created proxy on window.confirm.
like,
(function (proxied) {
window.confirm = function () {
var res = MyConfirm.apply(this, arguments);
return res;
};
})(window.confirm);
The problem is, MyConfirm is based on promise but where ever confirm is there, its acting as boolean. What would be proper solution for this situation? Is it possible to make a custom function which works exactly like window.confirm?
Is there anyway, we can return boolean or other values from a function which depends on an async call?
You may be able to get the desired behavior with a custom confirmation dialog, I created a custom dialog control a while ago that gave me the ability to have a flexible modal confirmation dialog. I created a full sample jsFiddle here. For my needs, the dialog was part of a common js library and displays as soon as you instantiate it, and can include options for content, size, and confirmation button callbacks, but you could have a confirm function on the dialog object that does the work to initialize and display it, and return a response. Here's the complete code, which is also in the jsFiddle...
// Launch the dialog from a click on an element on the page
$("#launchDialog").click(function () {
showConfirmDialog();
})
function showConfirmDialog() {
//Define the dialog options
var dlgOptions = {
width: 300,
height: 150,
modal: true,
confirm: true,
confirmopts: {
closeOnOk: true,
question: "Are you sure?",
buttons: {
Ok: {
Label: "OK",
callback: dialogOkCallback
},
Cancel: {
Label: "Cancel",
callback: dialogCancelCallback
},
}
}
}
// Initialize the dialog object and display it
var dlg = MySite.Common.createDialog("confirmDialog", "Confirmation Required", "<p>Some additional dialog content here</p>", dlgOptions, document);
}
// Handle the OK response
function dialogOkCallback() {
$("#dialogresult").html("You clicked Ok");
}
// Handle the Cancel response
function dialogCancelCallback() {
$("#dialogresult").html("You clicked Cancel");
}
// Common library with dialog code
if (typeof (MySite) == "undefined")
{ MySite = { __namespace: true }; }
MySite.Common = {
createDialog: function (tagId, title, content, options, documentobj) {
var dlg;
var dlgLeft;
var dlgTop;
// Defaults
var dlgWidth = 210;
var dlgHeight = 140;
var dlgConfirmation = "";
var dlgConfirmationContainerHTML = "";
var dlgConfirmationContainer;
var isNewDialog;
var docBody;
var dlgTag;
var dlgModalBg;
var docObj;
// Take the document object passed in or default it, this is where the dialog div will be anchored
if (documentobj) {
docObj = documentobj;
}
else {
docObj = document;
}
docBody = $(docObj.body);
// Process the options if available
if (options) {
if (options.width) {
dlgWidth = options.width;
}
if (options.height) {
dlgHeight = options.height;
}
if (options.modal) {
// Set up the background div if this is a modal dialog
dlgModalBg = $(docObj.getElementById("dialogModalBackground"));
if (dlgModalBg.length == 0) {
docBody.append("<div id='dialogModalBackground' style='background-color: #000000; z-index:9998; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; opacity: 0.3;'> </div>");
} else {
dlgModalBg = docBody.find("#dialogModalBackground");
dlgModalBg.show();
}
}
}
// Do some dialog positioning
dlgLeft = (docObj.body.clientWidth / 2) - (dlgWidth / 2);
dlgTop = (docObj.body.clientHeight / 2) - (dlgHeight / 2) - 50;
// Make sure the dialog top value doesn't go negative
dlgTop = Math.max(dlgTop, 0);
dlg = $(docObj.getElementById(tagId));
// Create the dialog div
if (dlg.length == 0) {
isNewDialog = true;
docBody.append("<div id='dialogContainer_" + tagId + "' style='width: " + dlgWidth + "px; min-height: " + dlgHeight + "px; background-color: #ffffff; border: 1px solid darkgrey; z-index: 9999; position: absolute; top: " + dlgTop + "px; left: " + dlgLeft + "px;'><p id='dlgHeader' class='draggable_handle' style='color: #FFFFFF; margin: 0px; padding: 5px 1px 1px 5px; height: 18px; background-color: #005f9f; font-weight: bold; font-size: 1.2em; font-family: Arial;'>" + title + "<span style='float: right; font-size: 0.8em; cursor: pointer; padding-right: 4px;' id='dialogClose_" + tagId + "'>Close</span></p><div style='padding: 0px; margin: 0px 2px 0px 2px; min-height: " + (dlgHeight - 24).toString() + "px;' id='" + tagId + "'></div></div>");
dlg = docBody.find("#" + tagId);
} else {
isNewDialog = false;
dlg.html("");
docBody.find("#dialogContainer_" + tagId).show();
}
// Make the dialog draggable if that feature is available
if ($.ui) {
if ($.ui.draggable) {
docBody.find("#dlgHeader").css("cursor", "move");
docBody.find("#dialogContainer_" + tagId).draggable({ handle: ".draggable_handle" });
}
}
if (content) {
dlg.html(content);
}
// Create or update the confirmation dialog content
dlgConfirmationContainer = docBody.find("#Confirmation_" + tagId);
// Set up the buttons if this is a confirmation dialog
if (options.confirm == true) {
if (options.confirmopts.question != null) {
dlgConfirmation += options.confirmopts.question + "<br/><br/>";
}
if (options.confirmopts.buttons.Ok.Label != null) {
dlgConfirmation += "<input id='dialogOk_" + tagId + "' style='width: 45%' type='button' value='" + options.confirmopts.buttons.Ok.Label + "'/> ";
}
if (options.confirmopts.buttons.Cancel != null && options.confirmopts.buttons.Cancel.Label != null) {
dlgConfirmation += "<input id='dialogCancel_" + tagId + "' style='width: 45%' type='button' value='" + options.confirmopts.buttons.Cancel.Label + "'/>";
}
if (dlgConfirmationContainer.length == 0) {
dlg.append("<div id='Confirmation_" + tagId + "' style='padding: 3px'>" + dlgConfirmation + "</div>");
} else {
dlgConfirmationContainer.show();
dlgConfirmationContainer.html(dlgConfirmation);
}
} else {
dlgConfirmationContainer.hide();
}
// Assign click events if this is a confirmation dialog. the jQuery click() assignment normally would APPEND click events to
// the object, but those are lost when the div container html is reassigned above, so we assign the click each time this function
// is called.
if (options.confirm) {
docBody.find("#dialogOk_" + tagId).click(function (event) {
event.preventDefault();
if (options.confirmopts.closeOnOk == true) {
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
}
if (!options.confirmopts.keepOnOk) {
docBody.find("#Confirmation_" + tagId).hide();
}
if (options.confirmopts.buttons.Ok.callback != null) {
options.confirmopts.buttons.Ok.callback();
}
});
docBody.find("#dialogCancel_" + tagId).click(function (event) {
event.preventDefault();
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
if (options.confirmopts.buttons.Cancel.callback != null) {
options.confirmopts.buttons.Cancel.callback();
}
});
}
docBody.find("#dialogClose_" + tagId).click(function (event) {
event.preventDefault();
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
});
dlg.closeDialog = function () {
docBody.find("#dialogContainer_" + tagId).hide();
docBody.find("#dialogModalBackground").hide();
};
return dlg;
},
__namespace: true
};

Issue with changing how containers look based on values in an MD array

I am currently changing how certain containers work based on if a value is met in the array and if a value is then located in a container in real time using socket and a bit of Jquery.
It works fine for a single web page, but when I open up two instances of the same web page, its starts replicating containers if I refresh the page, when there is no duplicate values in the array.
In the image below I clicked refresh on the left instance but then another container appears on the right when there should be only two. A value will keep being added every time I refresh the left page, but when I then refresh the right page it then only has two and the left side has three.
How the array looks:
[ [ 'User_488', null ],
[ 'User_487', 'disable' ],
[ 'User_477', 'disable' ],
[ 'User_490', 'disable' ],
[ '1000', 'enable', 'offline' ],
[ '1001', 'enable', 'online' ],
[ '1002', 'disable' ],
[ '1004', 'disable' ]]
Code which changes how the containers look based on the above array, and seems to be the source of the issue:
socket.on("eventsCalls", function (calldata) {
for (var i = 0; i < calldata.length; i++) {
if (calldata[i][0] && calldata[i][2] === "Ringing") {
$("div[class*='tile']:contains('" + calldata[i][0] + "')").removeClass("answer noanswer default").addClass("ring").attr('data-content', calldata[i][3]);
} else if (calldata[i][0] && calldata[i][2] === "Hangup") {
$("div[class*='tile']:not(.DND):contains('" + calldata[i][0] + "')").removeClass("answer noanswer default").addClass("hangup").attr('data-content', calldata[i][3]);
setTimeout(function () {
$("div[class*='tile']").removeClass("hangup");
}, 3000);
} else if (calldata[i][0] && calldata[i][2] === "ANSWER") {
$("div[class*='tile']:contains('" + calldata[i][0] + "')").removeClass("ring noanswer default").addClass("answer").attr('data-content', calldata[i][3]);
} else if (calldata[i][0] && calldata[i][2] === "NOANSWER") {
$("div[class*='tile']:contains('" + calldata[i][0] + "')").removeClass("ring default").addClass("noanswer").attr('data-content', calldata[i][3]);
} else if (calldata[i][0] && calldata[i][4] === "DND") {
$("div[class*='tile']:contains('" + calldata[i][0] + "')").removeClass("hangup default").addClass("DND");
} else if (calldata[i][0] && calldata[i][4] === "") {
$("div[class*='tile']:contains('" + calldata[i][0] + "')").removeClass("DND default");
}
}
});
socket.on("eventsRegister", function (regisdata) {
for (var i = 0; i < regisdata.length; i++) {
if (regisdata[i][2] === "online") {
$("div[class*='tile']:not(.answer .noanswer .ring .hangup):contains('" + regisdata[i][0] + "')").removeClass("ring default").css("background-color", "#78ff4d").html("<h6><img src='../images/online.png'> <b>" + regisdata[i][0] + "</b></h6><p><span></span></p>");
} else if (regisdata[i][2] === "offline") {
$("div[class*='tile']:not(.answer .noanswer .ring .hangup):contains('" + regisdata[i][0] + "')").removeClass("ring").addClass("default").css("background-color", "white").html("<h6><img src='../images/offline.png'> <b>" + regisdata[i][0] + "</b></h6><p><span></span></p>");
}
}
});
CSS
.default {
opacity: 0.4;
filter: alpha(opacity=40);
background-color: white;
}
.hangup {
background-color: LightSlateGray !important;
}
.hangup:after {
font-weight: bold;
font-size: 12px;
content: url('../images/hangup.png') " + " attr(data-content);
}
.answer {
background-color: orange !important;
}
.answer:after {
font-weight: bold;
font-size: 12px;
content: url('../images/Incall.png') " +" attr(data-content);
}
.noanswer {
background-color: #006666 !important;
}
.noanswer:after {
font-weight: bold;
font-size: 12px;
content: url('../images/busy.png') " +" attr(data-content);
}
.ring {
background-color: yellow !important;
}
.ring:after {
font-weight: bold;
font-size: 12px;
content: url('../images/ring.png') " +" attr(data-content);
}
.DND {
background-color: red !important;
}
.DND img {
display: none;
}
.DND h6:before {
content: url('../images/dnd.png');
}
Anyone have any ideas why this is happening, am currently stumped.
EDIT: JS Fiddle to emulate what is suppose to happen/ what its suppose to look like when there are multiple instances.
Found the issue and it was very minor, I was removing everything with a class of default which was being removed every time a state changed, so now it will remove everything with class tile and prevent any duplicate containers.
socket.on("presenceusers", function (userPresence) {
$('.tile').remove();\\ <------
for (var i = 0; i < userPresence.length; i++) {
if (userPresence[i][1] === "enable") {
$presence.append('<div class="col-md-2 md tile default"><h6><img src="../images/offline.png"><b>' + userPresence[i][0] + '</b></h6></div>');
}
}
});

Text in javascript div and click anywere to close div

I have a javascript which opens up a window just before a surfer enters my site which has 24 hours cookie meaning it will popup again after the surfer visits my site again after 24 hours.
Right now one can only close the div if the red "x" button is pressed. Also when I run it I can only add images or iframes but I'd like o add some text like "welcome to my site".
Here is the code
var floatingAd={
run: function (e, t) {
if (e === 2 || e === 1 && (this.getCookie("floatingAd") === null || this.getCookie("floatingAd") === "")) {
document.write('<div id="floatingAdFixed" style="bottom: 0px; background: #fff; font-family: Arial, Helvetica, sans-serif; left: 0; padding: 0px 0; position: fixed; font-size: 16px; width: 100%; z-index: 99999; float: left; vertical-align: middle; margin: 0px 0 0; opacity: 0.88; font-weight: bold;">');
document.write('<div style="text-align: right; width: 710px; margin: 340px auto;"><img onclick="floatingAd.close(' + e + ');" style="position: absolute; margin-top: -11px; margin-left: -23px; cursor: pointer;" src="data:image/png;base64,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"></div>');
document.write('<div id="floatingAd" style="text-align: center; width: 710px; margin: 300px auto; ">');
document.write("</div>");
document.write("</div>");
document.getElementById("floatingAd").innerHTML = t
}
},
close: function (e) {
if (e === 1) {
this.setCookie("floatingAd", 1, 1)
}
document.getElementById("floatingAdFixed").style.display = "none"
},
setCookie: function (t, n, r) {
var i = new Date;
i.setDate(i.getDate() + r);
var s = escape(n) + (r == null ? "" : "; expires=" + i.toUTCString());
document.cookie = t + "=" + s + ";path=/"
},
getCookie: function (e) {
var t = document.cookie;
var n = t.indexOf(" " + e + "=");
if (n == -1) {
n = t.indexOf(e + "=")
}
if (n == -1) {
t = null
} else {
n = t.indexOf("=", n) + 1;
var r = t.indexOf(";", n);
if (r == -1) {
r = t.length
}
t = unescape(t.substring(n, r))
}
return t
}
}
/**
* Run the script
* 1 = 24 hours cookie, 2 = refresh
*/
floatingAd.run(1, '');
Two questions:
How do I make it to close if you click anywhere on the screen?
Hwo do I make it to show text in the floatingAd.run(1, '');?
For 1 check out How do I detect a click outside an element?
EDIT: If you would like to have the window closed if "you click anywhere on the screen", just use your object in the following way:
$('html').click(function() {
// You may skip the following if statement, it may work without it
if (document.getElementById("floatingAdFixed").style.display != "none")
// The following line is what you'll definitely need
floatingAd.close(1);
});
For 2, just add it as another variable in run like this
var floatingAd={
run: function (e, t, text) {
// ...
document.write('<div id="textContainer">' + text + '</div>');
// ...
}
Then use it like this:
floatingAd.run(1, '', 'Writing some text');
DEMO HERE

Pagination Alternatives

I am looking for ideas for pagination alternatives. I am aware of 2 pagination schemes:
Click on pages pagination - my favorite example
Infinite scroll pagination - one implementation here that seems to work
There must be some other less known/popular ways to do it. Bonus points if you can provide a link to a demo
Thanks
I think that a good alternative to paging is a way, or more than one way, for the user to tell the server something about what it is they're looking for. For some types of content (like, a whole lot of text, say from a research paper or a work of fiction), of course you're probably stuck with paging. But when the content is naturally searchable (like tables of checking account transactions), good, simple filtering tools are probably more useful than pagination schemes. (Actually you may need both.)
I worked on a GWT hybrid technique where it did an "infinite scroll" but only showed a "window/page" of information at a time. So it only loaded a fixed amount of data to the browser at any given time. If you could display 20 items and scrolled it just updated the list 20 items at a time. Paging without paging, scrolling without scrolling.
Of course this is a trivial definition of the actual implementation, which was much smarter than this sounds and very optimized for round trips. And this was a list of results that was already filtered down with search criteria. They go hand in hand.
Take a look at 'logarithmic' pagination, as described in my answer here:
How to do page navigation for many, many pages? Logarithmic page navigation
It's like regular pagination, but solves the problem of getting to pages in the middle of a '...' range without many repeated mouseclicks. i.e. How long would it take to get to page 2456 out of 10380 if these are your links: 1 2 3 4 5 ... 10376 10377 10378 10379 10380 ?
(But, Pointy has, uhm... a point also (!))
Here is the code for a pure JavaScript pagination control I built recently. It is similar to your favorite with these added benefits...
Clicking the ... allows quick jump to any page
No words means no localization (next, prev, first, last buttons aren't
needed in this simple control)
No dependencies (jQuery not required)
var Pagination = {
code: '',
Extend: function(data) {
data = data || {};
Pagination.size = data.size || 300;
Pagination.page = data.page || 1;
Pagination.step = data.step || 3;
},
Add: function(s, f) {
for (var i = s; i < f; i++) {
Pagination.code += '<a>' + i + '</a>';
}
},
Last: function() {
Pagination.code += '<i>...</i><a>' + Pagination.size + '</a>';
},
First: function() {
Pagination.code += '<a>1</a><i>...</i>';
},
Click: function() {
Pagination.page = +this.innerHTML;
Pagination.Start();
},
Prev: function() {
Pagination.page--;
if (Pagination.page < 1) {
Pagination.page = 1;
}
Pagination.Start();
},
Next: function() {
Pagination.page++;
if (Pagination.page > Pagination.size) {
Pagination.page = Pagination.size;
}
Pagination.Start();
},
TypePage: function() {
Pagination.code = '<input onclick="this.setSelectionRange(0, this.value.length);this.focus();" onkeypress="if (event.keyCode == 13) { this.blur(); }" value="' + Pagination.page + '" /> / ' + Pagination.size;
Pagination.Finish();
var v = Pagination.e.getElementsByTagName('input')[0];
v.click();
v.addEventListener("blur", function(event) {
var p = parseInt(this.value);
if (!isNaN(parseFloat(p)) && isFinite(p)) {
if (p > Pagination.size) {
p = Pagination.size;
} else if (p < 1) {
p = 1;
}
} else {
p = Pagination.page;
}
Pagination.Init(document.getElementById('pagination'), {
size: Pagination.size,
page: p,
step: Pagination.step
});
}, false);
},
Bind: function() {
var a = Pagination.e.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
if (+a[i].innerHTML === Pagination.page) a[i].className = 'current';
a[i].addEventListener('click', Pagination.Click, false);
}
var d = Pagination.e.getElementsByTagName('i');
for (i = 0; i < d.length; i++) {
d[i].addEventListener('click', Pagination.TypePage, false);
}
},
Finish: function() {
Pagination.e.innerHTML = Pagination.code;
Pagination.code = '';
Pagination.Bind();
},
Start: function() {
if (Pagination.size < Pagination.step * 2 + 6) {
Pagination.Add(1, Pagination.size + 1);
} else if (Pagination.page < Pagination.step * 2 + 1) {
Pagination.Add(1, Pagination.step * 2 + 4);
Pagination.Last();
} else if (Pagination.page > Pagination.size - Pagination.step * 2) {
Pagination.First();
Pagination.Add(Pagination.size - Pagination.step * 2 - 2, Pagination.size + 1);
} else {
Pagination.First();
Pagination.Add(Pagination.page - Pagination.step, Pagination.page + Pagination.step + 1);
Pagination.Last();
}
Pagination.Finish();
},
Buttons: function(e) {
var nav = e.getElementsByTagName('a');
nav[0].addEventListener('click', Pagination.Prev, false);
nav[1].addEventListener('click', Pagination.Next, false);
},
Create: function(e) {
var html = [
'<a>◄</a>', // previous button
'<span></span>', // pagination container
'<a>►</a>' // next button
];
e.innerHTML = html.join('');
Pagination.e = e.getElementsByTagName('span')[0];
Pagination.Buttons(e);
},
Init: function(e, data) {
Pagination.Extend(data);
Pagination.Create(e);
Pagination.Start();
}
};
var init = function() {
Pagination.Init(document.getElementById('pagination'), {
size: 30, // pages size
page: 1, // selected page
step: 2 // pages before and after current
});
};
document.addEventListener('DOMContentLoaded', init, false);
html {
height: 100%;
width: 100%;
background-color: #ffffff;
}
body {
margin: 0;
height: 100%;
width: 100%;
text-align: center;
font-family: Arial, sans-serif;
}
body:before {
content: '';
display: inline-block;
width: 0;
height: 100%;
vertical-align: middle;
}
#pagination {
display: inline-block;
vertical-align: middle;
padding: 1px 2px 4px 2px;
font-size: 12px;
color: #7D7D7D;
}
#pagination a,
#pagination i {
display: inline-block;
vertical-align: middle;
width: 22px;
color: #7D7D7D;
text-align: center;
padding: 4px 0;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
#pagination a {
margin: 0 2px 0 2px;
cursor: pointer;
}
#pagination a:hover {
background-color: #999;
color: #fff;
}
#pagination i {
border: 2px solid transparent;
cursor: pointer;
}
#pagination i:hover {
border: 2px solid #999;
cursor: pointer;
}
#pagination input {
width: 40px;
padding: 2px 4px;
color: #7D7D7D;
text-align: right;
}
#pagination a.current {
border: 1px solid #E9E9E9;
background-color: #666;
color: #fff;
}
<div id="pagination"></div>
There's a cool logarithmic pagination solution here:
http://jobcloud.cz/glPagiSmart.jc
But I'm not sure how many people would actually want to use the hex or binary implementations :)

Categories