I'm using a jquery plugin called quicksearch within Sharepoint 2010 and it works perfectly. Unfortunately were being forced to migrate onto sharepoint 2013 and it's stopped working. An error is shown saying that the function is undefined. I believe I've narrowed this down to the quicksearch function itself.
Here is the preliminary code:
_spBodyOnLoadFunctionNames.push("Load");
$('[name=search]').on('keyup', function(){
Load();
});
function Load() {
var searchArea = "#cbqwpctl00_ctl22_g_ca6bb172_1ab4_430d_ae38_a32cfa03b56b ul li";
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
$('.filter input').on('change', function(){
checkAndHide()
//$(searchArea).unhighlight();
});
function checkAndHide(){
var inputs = $('.filter input');
var i =0;
for (var i = 0; i < inputs.length; i++){
if (!inputs[i].checked){
$('.' + inputs[i].name).addClass('filter-hide');
} else {
$('.' + inputs[i].name).removeClass('filter-hide');
};
};
};
}
Here is an example of the quicksearch library I'm using:
(function($, window, document, undefined) {
$.fn.quicksearch = function (target, opt) {
var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({
delay: 300,
selector: null,
stripeRows: null,
loader: null,
noResults: 'div#noresults',
bind: 'keyup keydown',
onBefore: function () {
var ar = $('input#id_search_list').val()
if (ar.length > 2) {
var i=0;
var ar2 = $('input#id_search_list').val().split(" ");
for (i = 0; i < ar2.length; i++) {
$(searchArea + ':visible');
}
return true;
}
return false;
checkAndHide()
},
onAfter: function () {
return;
},
show: function () {
this.style.display = "block";
},
hide: function () {
this.style.display = "none";
},
prepareQuery: function (val) {
return val.toLowerCase().split(' ');
},
testQuery: function (query, txt, _row) {
for (var i = 0; i < query.length; i += 1) {
if (txt.indexOf(query[i]) === -1) {
return false;
}
}
return true;
}
}, opt);
this.go = function () {
var i = 0,
noresults = true,
query = options.prepareQuery(val),
val_empty = (val.replace(' ', '').length === 0);
for (var i = 0, len = rowcache.length; i < len; i++) {
if (val_empty) {
options.hide.apply(rowcache[i]);
noresults = false;
} else if (options.testQuery(query, cache[i], rowcache[i])){
options.show.apply(rowcache[i]);
noresults = false;
} else {
options.hide.apply(rowcache[i]);
}
}
if (noresults) {
this.results(false);
} else {
this.results(true);
this.stripe();
}
this.loader(false);
options.onAfter();
return this;
};
this.stripe = function () {
if (typeof options.stripeRows === "object" && options.stripeRows !== null)
{
var joined = options.stripeRows.join(' ');
var stripeRows_length = options.stripeRows.length;
jq_results.not(':hidden').each(function (i) {
$(this).removeClass(joined).addClass(options.stripeRows[i % stripeRows_length]);
});
}
return this;
};
this.strip_html = function (input) {
var output = input.replace(new RegExp('<[^<]+\>', 'g'), "");
output = $.trim(output.toLowerCase());
return output;
};
this.results = function (bool) {
if (typeof options.noResults === "string" && options.noResults !== "") {
if (bool) {
$(options.noResults).hide();
} else {
$(options.noResults).show();
}
}
return this;
};
this.loader = function (bool) {
if (typeof options.loader === "string" && options.loader !== "") {
(bool) ? $(options.loader).show() : $(options.loader).hide();
}
return this;
};
this.cache = function () {
jq_results = $(target);
if (typeof options.noResults === "string" && options.noResults !== "") {
jq_results = jq_results.not(options.noResults);
}
var t = (typeof options.selector === "string") ? jq_results.find(options.selector) : $(target).not(options.noResults);
cache = t.map(function () {
return e.strip_html(this.innerHTML);
});
rowcache = jq_results.map(function () {
return this;
});
return this.go();
};
this.trigger = function () {
this.loader(true);
if (options.onBefore()) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
e.go();
}, options.delay);
}
return this;
};
this.cache();
this.results(true);
this.stripe();
this.loader(false);
return this.each(function () {
$(this).bind(options.bind, function () {
val = $(this).val();
e.trigger();
});
});
};
}(jQuery, this, document));
`
This is where the error comes up:
var qs = $('input#id_search_list').val();
qs.quicksearch(searchArea);
Any help would be appreciated
Turns out was a small issue in the code and major css as sharepoint plays differently in 2013
Related
I am getting the following error on all browsers while opening the float box and then it cannot be closed. You need to refresh the page. There was no problem before. It was working fine. Now, I've been getting this error ever since I adapted the new design to the site. How can fix this problem? Thank you.
Uncaught TypeError: Cannot read property 'show' of undefined
// disabling/enabling
jQuery.fn.extend({
disable: function() {
this.each(function()
{
this.disabled = true;
if ( this.tagName != 'INPUT' && this.tagName != 'TEXTAREA' && this.tagName != 'SELECT' )
{
this.jQuery_disabled_clone =
jQuery(this)
.addClass('disabled')
.clone()
.removeAttr('id')
.get(0);
jQuery(this)
.hide()
.bind('unload', function(){
jQuery(this).enable();
})
.after(this.jQuery_disabled_clone);
}
});
return this;
},
enable: function()
{
this.each(function()
{
this.disabled = false;
if ( this.jQuery_disabled_clone )
{
jQuery(this.jQuery_disabled_clone).remove();
this.jQuery_disabled_clone = null;
jQuery(this)
.unbind('unload', function(){
jQuery(this).enable();
})
.removeClass('disabled')
.show();
}
});
return this;
}
});
function SK_Exception(message, code)
{
this.toString = function() {
return message;
}
this.getCode = function() {
return code;
}
}
function SK_drawError(err_msg, delay) {
SK_drawMessage(err_msg, 'error', delay);
}
function SK_drawMessage(msg_text, type, delay)
{
if (navigator.appName == 'Microsoft Internet Explorer' && (msg_text == "Virtual gift has been sent" || msg_text == "Hediyeniz başarıyla gönderildi.." || msg_text == "Virtual gift has not been sent" || msg_text == "Hediyeniz gönderilemedi.."))
alert(msg_text);
type = type || 'message';
delay = delay || (1000*10);
if (SK_drawMessage.in_process) {
if (msg_text) {
SK_drawMessage.queue.unshift([msg_text, type, delay]);
}
return;
}
if (!msg_text) {
var item = SK_drawMessage.queue.shift();
if (!item) {
return;
}
msg_text = item[0];
type = item[1];
delay = item[2];
}
SK_drawMessage.in_process = true;
// getting draw position
var $last = jQuery('.macos_msg_node:last');
var top_pos = (!$last.length) ? 0 : $last.position().top + $last.outerHeight() + 2;
var $msg_block =
// creating message block
jQuery('<div class="macos_msg_node macos_'+type+'" style="display: none"></div>')
.appendTo('body')
.html(msg_text)
.prepend('<a class="close_btn" href="#"></a>')
.css('top', top_pos)
.fadeTo(50, 0.1, function() {
jQuery(this).css('display', '');
SK_drawMessage.in_process = false;
SK_drawMessage();
jQuery(this).fadeTo(300, 1, function() {
if (delay > 0) {
window.setTimeout(function() {
try {
$msg_block.fadeOut(2500, function() {
jQuery(this).remove();
});
} catch (e) {alert(e);}
}, delay);
}
});
});
$msg_block.children('.close_btn')
.click(function() {
jQuery(this).parent().fadeOut(100, function() {
jQuery(this).remove();
});
return false;
}
);
}
SK_drawMessage.in_process = false;
SK_drawMessage.queue = [];
/**
* Float box constructor.
*
* #param string|jQuery $title
* #param string|jQuery $contents
* #param jQuery $controls
* #param object position {top, left} = center
* #param integer width = auto
* #param integer height = auto
*/
function SK_FloatBox(options)
{
var fb_class;
if (typeof document.body.style.maxHeight === 'undefined') { //if IE 6
jQuery('body').css({height: '100%', width: '100%'});
jQuery('html').css('overflow', 'hidden');
if (document.getElementById('floatbox_HideSelect') === null) { //iframe to hide select elements in ie6
jQuery('body').append('<iframe id="floatbox_HideSelect"></iframe><div id="floatbox_overlay"></div>');
fb_class = SK_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
jQuery('#floatbox_overlay').addClass(fb_class);
}
}
else { //all others
if (document.getElementById('floatbox_overlay') === null) {
jQuery('body').append('<div id="floatbox_overlay"></div>');
fb_class = SK_FloatBox.detectMacXFF() ? 'floatbox_overlayMacFFBGHack' : 'floatbox_overlayBG';
jQuery('#floatbox_overlay').addClass(fb_class);
}
}
jQuery('body').css('overflow', 'hidden');
this.$container = jQuery('.floatbox_container', '#sk-floatbox-block-prototype').clone().appendTo('body');
this.$header = this.$container.find('.block_cap_title');
if (typeof options.$title == 'string') {
options.$title = jQuery('<span>'+options.$title+'</span>');
}
else {
this.$title_parent = options.$title.parent();
}
this.$header.append(options.$title);
this.$body = this.$container.find('.block_body_c');
if (typeof options.$contents == 'string') {
options.$contents = jQuery('<span>'+options.$contents+'</span>');
}
else {
this.$contents_parent = options.$contents.parent();
}
this.$body.append(options.$contents);
this.$bottom = this.$container.find('.block_bottom_c');
if (options.$controls) {
if (typeof options.$controls == 'string') {
options.$controls = jQuery('<span>'+options.$controls+'</span>');
}
else {
this.$controls_parent = options.$controls.parent();
}
this.$bottom.append(options.$controls);
}
if (options.width)
this.$container.css("width", options.width);
if (options.height)
this.$container.css("height", options.height);
var fl_box = this;
jQuery('.close_btn', this.$container.find('.floatbox_header'))
.one('click', function() {
fl_box.close();
return false;
});
this.esc_listener =
function(event) {
if (event.keyCode == 27) {
fl_box.close();
return false;
}
return true;
}
jQuery(document).bind('keydown', this.esc_listener);
this.$container
.fadeTo(1, 0.1, function()
{
var $this = jQuery(this);
$this.css('display', 'block');
if (options.position) {
$this.css(options.position);
}
else {
var position = {
top:((jQuery(window).height()/2) - ($this.height()/2))/*.ceil()*/,
left:((jQuery(window).width()/2) - ($this.width()/2))/*.ceil()*/
};
$this.css(position);
}
// trigger on show event
fl_box.trigger('show');
$this.fadeTo(100, 1);
});
this.events = {close: [], show: []};
}
SK_FloatBox.detectMacXFF = function()
{
var userAgent = navigator.userAgent.toLowerCase();
return (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1);
}
SK_FloatBox.prototype = {
close: function()
{
if (this.trigger('close') === false) {
return false;
}
jQuery(document).unbind('keydown', this.esc_listener);
if (this.$title_parent && this.$title_parent.length) {
this.$title_parent.append(
this.$header.children()
);
}
if (this.$contents_parent && this.$contents_parent.length) {
this.$contents_parent.append(this.$body.children());
}
if (this.$controls_parent && this.$controls_parent.length) {
this.$controls_parent.append(this.$bottom.children());
}
this.$container.remove();
if (jQuery('.floatbox_container:not("#sk-floatbox-block-prototype .floatbox_container")').length === 0) {
jQuery('body').css('overflow', '');
jQuery('#floatbox_overlay, #floatbox_HideSelect').remove();
}
return true;
},
bind: function(type, func)
{
if (this.events[type] == undefined) {
throw 'form error: unknown event type "'+type+'"';
}
this.events[type].push(func);
},
trigger: function(type, params)
{
if (this.events[type] == undefined) {
throw 'form error: unknown event type "'+type+'"';
}
params = params || [];
for (var i = 0, func; func = this.events[type][i]; i++) {
if (func.apply(this, params) === false) {
return false;
}
}
return true;
}
}
function SK_alert($title, $contents, callback)
{
if (!callback &&
typeof $contents == 'function' &&
$contents.constructor != Array) {
callback = $contents;
}
if (!$contents || $contents == callback) {
$contents = $title;
$title = SK_Language.text('%interface.alert_title');
}
var $ok_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.ok'));
var fl_box = new SK_FloatBox({
$title: $title,
$contents: $contents,
$controls: $ok_btn
});
$ok_btn.one('click', function() {
fl_box.close();
if (callback) {
callback.apply(fl_box);
}
});
return fl_box;
}
function SK_confirm($title, $contents, callback)
{
if (!callback &&
typeof $contents == 'function' &&
$contents.constructor != Array) {
callback = $contents;
}
if (!$contents || $contents == callback) {
$contents = $title;
$title = SK_Language.text('%interface.confirmation_title');
}
var $ok_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.ok'));
var $cancel_btn =
jQuery('<input type="button" />')
.val(SK_Language.text('%interface.cancel'));
var fl_box = new SK_FloatBox({
$title: $title,
$contents: $contents,
$controls: jQuery($ok_btn)
.add('<span> </span>')
.add($cancel_btn)
});
$ok_btn.one('click', function() {
fl_box.close();
if (callback) {
callback.apply(fl_box);
}
});
$cancel_btn.one('click', function() {
fl_box.close();
});
return fl_box;
}
function SK_BlockHandler(block_node)
{
this.$block = jQuery(block_node);
this.$block_cap =
jQuery('.block_cap:eq(0)', this.$block);
this.$title =
jQuery('.block_cap_title:eq(0)', this.$block_cap);
this.$body =
jQuery('.block_body:eq(0)', this.$block);
this.$expand_btn =
jQuery('.block_expand:eq(0), .block_collapse:eq(0)', this.$block_cap);
this.events = {
click: [],
expand: [],
collapse: []
}
var handler = this;
this.$block_cap
.click(function() {
if (handler.$expand_btn.hasClass('block_expand')) {
handler.expand();
}
else if (handler.$expand_btn.hasClass('block_collapse')) {
handler.collapse();
}
return false;
});
}
SK_BlockHandler.prototype = {
expand: function(trigger_events)
{
if (trigger_events === undefined) {
trigger_events = true;
}
if (!trigger_events || (
this.trigger('expand') !== false
&& this.trigger('click') !== false)
) {
this.$expand_btn.attr('class', 'block_collapse');
this.$body.slideDown('fast');
}
return this;
},
collapse: function(trigger_events)
{
if (trigger_events === undefined) {
trigger_events = true;
}
if (!trigger_events || (
this.trigger('collapse') !== false
&& this.trigger('click') !== false)
) {
this.$expand_btn.attr('class', 'block_expand');
this.$body.slideUp('fast');
}
return this;
},
show: function(speed, callback) {
this.$block.show(speed, callback);
},
hide: function(speed, callback) {
this.$block.hide(speed, callback);
},
bind: function(type, arg1, arg2)
{
if (this.events[type] == undefined) {
throw 'block error: unknown event type "'+type+'"';
}
if (!arg2) {
this.events[type].push([arg1]);
}
else {
this.events[type].push([arg1, arg2]);
}
},
trigger: function(type)
{
if (this.events[type] == undefined) {
throw 'block error: unknown event type "'+type+'"';
}
for (var i = 0, item; item = this.events[type][i]; i++)
{
if (item.length == 1) {
if (item[0].apply(this) === false) {
return false;
}
}
else if (item[1].call(this, item[0]) === false) {
return false;
}
}
return true;
},
clone: function(clone_e)
{
var $clone = this.$block.clone();
var node = $clone.get(0);
node.sk_block_handler = new SK_BlockHandler(node);
if (clone_e) {
node.sk_block_handler.events = this.events;
}
return node.sk_block_handler;
},
append: function(content) {
return this.$body.append(content);
return this;
},
appendTo: function(content) {
this.$block.appendTo(content);
return this;
},
empty: function() {
this.$body.empty();
return this;
},
children: function(expr) {
return this.$body.children(expr).not('.block_body_corner');
},
find: function(expr) {
return this.$body.find(expr).not('.block_body_corner');
},
removeAttr: function(name) {
this.$block.removeAttr(name);
return this;
},
addClass: function(cls) {
this.$block.addClass(cls);
return this;
},
removeClass: function(cls) {
this.$block.removeClass(cls);
return this;
}
}
jQuery(function() {
jQuery('.block_expand, .block_collapse')
.each(function() {
var block_node = this.parentNode.parentNode.parentNode.parentNode;
if (jQuery(block_node).hasClass('block')) {
block_node.sk_block_handler = new SK_BlockHandler(block_node);
}
});
});
SK_Language = {
data: {},
text: function(lang_addr, var_list)
{
if ( SK_Language.data[lang_addr] === undefined ) {
throw new SK_Exception('language section ['+lang_addr+'] not found');
}
var text = SK_Language.data[lang_addr];
if (var_list) {
for ( key in var_list ) {
text = text.replace('{$'+key+'}', var_list[key]);
}
}
return text;
}
}
function nl2br(str) {
return (str + '').replace(/([^>]?)\n/g, '$1<br />\n');
}
function SK_SignIn() {
return window.sk_component_sign_in.showBox();
}
function SK_openIM(opponent_id, is_esd)
{
if (is_esd)
is_esd_session = '&is_esd_session='+is_esd;
else
is_esd_session = '';
return window.open(
URL_MEMBER+'im.php?opponent_id='+opponent_id+is_esd_session,
'im_with_'+opponent_id,
'width='+SK_openIM.width+','+
'height='+SK_openIM.height+','+
'resizable=yes, location=no, scrollbars=no, status=no'
);
}
SK_openIM.width = 445;
SK_openIM.height = 460;
function SK_profileNote( event_id, opponent_id)
{
return window.open(
URL_MEMBER+'profile_note.php?event_id='+event_id+'&opponent_id='+opponent_id,
'note_'+opponent_id,
'width='+SK_profileNote.width+','+
'height='+SK_profileNote.height+','+
'resizable=yes, location=no, scrollbars=no, status=no'
);
}
SK_profileNote.width = 325;
SK_profileNote.height = 425;
SK_EventManager = {
events: {},
bind: function(event, callback)
{
if ( typeof this.events[event] == 'undefined' || this.events[event] === null)
{
this.events[event] = [];
}
this.events[event].push(callback);
},
trigger: function(event, eventObject)
{
if (typeof this.events[event] != 'undefined' && this.events[event] !== null)
{
for (var i = 0; i < this.events[event].length; i++)
{
if (typeof this.events[event][i] == 'function')
{
if (this.events[event][i](eventObject) === false)
{
return;
}
}
}
}
}
};
SK_SetFieldInvitation = function(id, label)
{
var $node = $('#' + id);
$node.addClass('input_invitation').val(label);
$node.focus(function() {
var v = $node.val();
$node.removeClass('input_invitation');
if ( v == label )
{
$node.val('');
}
}).blur(function() {
var v = $node.val();
if ( !v )
{
$node.addClass('input_invitation').val(label);
}
});
$($node.get(0).form).submit(function(){
if ( $node.val() != label )
{
$node.removeClass('input_invitation');
}
});
}
<div class="floatbox_container" style="overflow: visible; width: 320px; opacity: 0.1; display: block; top: 274px; left: 736px;">
<div class="block_cap floatbox_header"><div class="block_cap_r"><div class="block_cap_c clearfix"><h3 class="block_cap_title"><b>Şifremi unuttum!</b></h3><a class="close_btn" href="#"></a></div></div></div> <div class="floatbox_body">
<div class="fblock_body block_body">
<div class="fblock_body_r block_body_r">
<div class="fblock_body_c block_body_c">
<div class="block_info">Şifremi yenile</div><form id="form_3" method="post" onsubmit="return false;">
<label>E-posta</label>: <input id="form_3-email" name="email" type="text" maxlength="255">
<div id="form_3-email-container"></div>
<div class="controls center float_left">
<input id="form_3-send-button" type="submit" value="Gönder"> </div>
<div class="clr"></div>
</form></div>
</div>
</div>
</div>
<div class="floatbox_bottom">
<div class="block_bottom">
<div class="block_bottom_r">
<div class="block_bottom_c">
</div>
</div>
</div>
</div>
<div class="fblock_bottom">
<div class="fblock_bottom_r">
<div class="fblock_bottom_c"></div>
</div>
</div>
</div>
I am using ELA bootstrap admin template.
There is a sidebarmenu.js file included in the theme which is used for sidebar menu List Open/Close. Every thing works file. But I wanted to implement Bootstrap Modal, inside my application. On button click, modal pops up but 'x' or close button seems to be not working. Nether it closes on clicking outside the modal area.
When I comment out inclusion of sidebarmenu.js from the header, the modal works fine.
Here is sidebarmenu.js code:
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['jquery'], factory);
} else if (typeof exports !== "undefined") {
factory(require('jquery'));
} else {
var mod = {
exports: {}
};
factory(global.jquery);
global.metisMenu = mod.exports;
}
})(this, function (_jquery) {
'use strict';
var _jquery2 = _interopRequireDefault(_jquery);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Util = function ($) {
var transition = false;
var TransitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
function getSpecialTransitionEndEvent() {
return {
bindType: transition.end,
delegateType: transition.end,
handle: function handle(event) {
if ($(event.target).is(this)) {
return event.handleObj.handler.apply(this, arguments);
}
return undefined;
}
};
}
function transitionEndTest() {
if (window.QUnit) {
return false;
}
var el = document.createElement('mm');
for (var name in TransitionEndEvent) {
if (el.style[name] !== undefined) {
return {
end: TransitionEndEvent[name]
};
}
}
return false;
}
function transitionEndEmulator(duration) {
var _this2 = this;
var called = false;
$(this).one(Util.TRANSITION_END, function () {
called = true;
});
setTimeout(function () {
if (!called) {
Util.triggerTransitionEnd(_this2);
}
}, duration);
return this;
}
function setTransitionEndSupport() {
transition = transitionEndTest();
$.fn.emulateTransitionEnd = transitionEndEmulator;
if (Util.supportsTransitionEnd()) {
$.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
}
}
var Util = {
TRANSITION_END: 'mmTransitionEnd',
triggerTransitionEnd: function triggerTransitionEnd(element) {
$(element).trigger(transition.end);
},
supportsTransitionEnd: function supportsTransitionEnd() {
return Boolean(transition);
}
};
setTransitionEndSupport();
return Util;
}(jQuery);
var MetisMenu = function ($) {
var NAME = 'metisMenu';
var DATA_KEY = 'metisMenu';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 350;
var Default = {
toggle: true,
preventDefault: true,
activeClass: 'active',
collapseClass: 'collapse',
collapseInClass: 'in',
collapsingClass: 'collapsing',
triggerElement: 'a',
parentTrigger: 'li',
subMenu: 'ul'
};
var Event = {
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var MetisMenu = function () {
function MetisMenu(element, config) {
_classCallCheck(this, MetisMenu);
this._element = element;
this._config = this._getConfig(config);
this._transitioning = null;
this.init();
}
MetisMenu.prototype.init = function init() {
var self = this;
$(this._element).find(this._config.parentTrigger + '.' + this._config.activeClass).has(this._config.subMenu).children(this._config.subMenu).attr('aria-expanded', true).addClass(this._config.collapseClass + ' ' + this._config.collapseInClass);
$(this._element).find(this._config.parentTrigger).not('.' + this._config.activeClass).has(this._config.subMenu).children(this._config.subMenu).attr('aria-expanded', false).addClass(this._config.collapseClass);
$(this._element).find(this._config.parentTrigger).has(this._config.subMenu).children(this._config.triggerElement).on(Event.CLICK_DATA_API, function (e) {
var _this = $(this);
var _parent = _this.parent(self._config.parentTrigger);
var _siblings = _parent.siblings(self._config.parentTrigger).children(self._config.triggerElement);
var _list = _parent.children(self._config.subMenu);
if (self._config.preventDefault) {
e.preventDefault();
}
if (_this.attr('aria-disabled') === 'true') {
return;
}
if (_parent.hasClass(self._config.activeClass)) {
_this.attr('aria-expanded', false);
self._hide(_list);
} else {
self._show(_list);
_this.attr('aria-expanded', true);
if (self._config.toggle) {
_siblings.attr('aria-expanded', false);
}
}
if (self._config.onTransitionStart) {
self._config.onTransitionStart(e);
}
});
};
MetisMenu.prototype._show = function _show(element) {
if (this._transitioning || $(element).hasClass(this._config.collapsingClass)) {
return;
}
var _this = this;
var _el = $(element);
var startEvent = $.Event(Event.SHOW);
_el.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
_el.parent(this._config.parentTrigger).addClass(this._config.activeClass);
if (this._config.toggle) {
this._hide(_el.parent(this._config.parentTrigger).siblings().children(this._config.subMenu + '.' + this._config.collapseInClass).attr('aria-expanded', false));
}
_el.removeClass(this._config.collapseClass).addClass(this._config.collapsingClass).height(0);
this.setTransitioning(true);
var complete = function complete() {
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass + ' ' + _this._config.collapseInClass).height('').attr('aria-expanded', true);
_this.setTransitioning(false);
_el.trigger(Event.SHOWN);
};
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
_el.height(_el[0].scrollHeight).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
};
MetisMenu.prototype._hide = function _hide(element) {
if (this._transitioning || !$(element).hasClass(this._config.collapseInClass)) {
return;
}
var _this = this;
var _el = $(element);
var startEvent = $.Event(Event.HIDE);
_el.trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
_el.parent(this._config.parentTrigger).removeClass(this._config.activeClass);
_el.height(_el.height())[0].offsetHeight;
_el.addClass(this._config.collapsingClass).removeClass(this._config.collapseClass).removeClass(this._config.collapseInClass);
this.setTransitioning(true);
var complete = function complete() {
if (_this._transitioning && _this._config.onTransitionEnd) {
_this._config.onTransitionEnd();
}
_this.setTransitioning(false);
_el.trigger(Event.HIDDEN);
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass).attr('aria-expanded', false);
};
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
_el.height() == 0 || _el.css('display') == 'none' ? complete() : _el.height(0).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
};
MetisMenu.prototype.setTransitioning = function setTransitioning(isTransitioning) {
this._transitioning = isTransitioning;
};
MetisMenu.prototype.dispose = function dispose() {
$.removeData(this._element, DATA_KEY);
$(this._element).find(this._config.parentTrigger).has(this._config.subMenu).children(this._config.triggerElement).off('click');
this._transitioning = null;
this._config = null;
this._element = null;
};
MetisMenu.prototype._getConfig = function _getConfig(config) {
config = $.extend({}, Default, config);
return config;
};
MetisMenu._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
var _config = $.extend({}, Default, $this.data(), (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config);
if (!data && /dispose/.test(config)) {
this.dispose();
}
if (!data) {
data = new MetisMenu(this, _config);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
};
return MetisMenu;
}();
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = MetisMenu._jQueryInterface;
$.fn[NAME].Constructor = MetisMenu;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return MetisMenu._jQueryInterface;
};
return MetisMenu;
}(jQuery);
});
I don't know why this code is having conflict with the dismissal of bootstrap modal dialog. Since, I am beginner in JavaScript/JQuery I am unable to find which section of above code is causing problem.
Thanks in advance.
I have a list of div's all with a set and equal height/width that are float:left so they sit next to each other and fold under if that parent is smaller than the combined with of the items.
Pretty standard.
This is to create a list of the twitter bootstrap icons, it gives something like this:
I have added next/previous keyboard navigation using the code below, however you will notice that the up/down arrow keys are mapped to call the left/right functions. What I have no idea how to do is to actually do the up/down navigation?
JsFiddle
(function ($) {
$.widget("ui.iconSelect", {
// default options
options: {
},
$select: null,
$wrapper: null,
$list: null,
$filter: null,
$active: null,
icons: {},
keys: {
left: 37,
up: 38,
right: 39,
down: 40
},
//initialization function
_create: function () {
var that = this;
that.$select = that.element;
that.$wrapper = $('<div class="select-icon" tabindex="0"></div>');
that.$filter = $('<input class="span12" tabindex="-1" placeholder="Filter by class name..."/>').appendTo(that.$wrapper);
that.$list = $('<div class="select-icon-list"></div>').appendTo(that.$wrapper);
//build the list of icons
that.element.find('option').each(function () {
var $option = $(this);
var icon = $option.val();
that.icons[icon] = $('<a data-class="' + icon + '"><i class="icon ' + icon + '"></i></a>');
if ($option.is(':selected')) {
that.icons[icon].addClass('selected active');
}
that.$list.append(that.icons[icon]);
});
that.$wrapper.insertBefore(that.$select);
that.$select.addClass('hide');
that._setupArrowKeysHandler();
that._setupClickHandler();
that._setupFilter();
that.focus('selected');
},
focus: function (type) {
var that = this;
if (that.$active === null || that.$active.length == 0) {
if (type == 'first') {
that.$active = that.$list.find('a:visible:first');
} else if (type == 'last') {
that.$active = that.$list.find('a:visible:last');
} else if (type == 'selected') {
that.$active = that.$list.find('a.selected:visible:first');
that.focus('first');
}
}
that.$active.addClass('active');
var toScroll = ((that.$list.scrollTop() + that.$active.position().top)-that.$list.height()/2)+that.$active.height()/2;
//that.$list.scrollTop((that.$list.scrollTop() + top)-that.$list.height()/2);
that.$list.stop(true).animate({
scrollTop: toScroll,
queue: false,
easing: 'linear'
}, 200);
if (type === 'selected') {
return false;
}
that.$select.val(that.$active.data('class'));
that.$select.trigger('change');
},
_setupArrowKeysHandler: function () {
var that = this;
that.$wrapper.on('keydown', function (e) {
switch (e.which) {
case that.keys.left:
that.moveLeft();
break;
case that.keys.up:
that.moveUp();
break;
case that.keys.right:
that.moveRight();
break;
case that.keys.down:
that.moveDown();
break;
case 16:
return true;
case 9:
return true;
break;
default:
that.$filter.focus();
return true;
}
return false;
});
},
_setupFilter: function(){
var that = this;
that.$filter.on('keydown keyup keypress paste cut change', function(e){
that.filter(that.$filter.val());
});
},
_setupClickHandler: function () {
var that = this;
that.$list.on('click', 'a', function () {
that.$wrapper.focus();
that.$active.removeClass('active');
that.$active = $(this);
that.focus('first');
});
},
moveUp: function () {
var that = this;
return that.moveLeft();
},
moveDown: function () {
var that = this;
return that.moveRight();
},
moveLeft: function () {
var that = this;
that.$active.removeClass('active');
that.$active = that.$active.prevAll(':visible:first');
that.focus('last');
return false;
},
moveRight: function () {
var that = this;
that.$active.removeClass('active');
that.$active = that.$active.nextAll(':visible:first');
that.focus('first');
return false;
},
filter: function(word){
var that = this;
var regexp = new RegExp(word.toLowerCase());
var found = false;
$.each(that.icons, function(i, $v){
found = regexp.test(i);
if(found && !$v.is(':visible')){
$v.show();
} else if(!found && $v.is(':visible')){
$v.hide();
}
});
}
});
})(jQuery);
Perhaps something like this: http://jsfiddle.net/QFzCY/
var blocksPerRow = 4;
$("body").on("keydown", function(e){
var thisIndex = $(".selected").index();
var newIndex = null;
if(e.keyCode === 38) {
// up
newIndex = thisIndex - blocksPerRow;
}
else if(e.keyCode === 40) {
// down
newIndex = thisIndex + blocksPerRow;
}
if(newIndex !== null) {
$(".test").eq(newIndex).addClass("selected").siblings().removeClass("selected");
}
});
Basically, you set how many items there are in a row and then find the current index and subtract or add that amount to select the next element via the new index.
If you need to know how many blocks per row there are, you could do this:
var offset = null;
var blocksPerRow = 0;
$(".test").each(function(){
if(offset === null) {
offset = $(this).offset().top;
}
else if($(this).offset().top !== offset) {
return false;
}
blocksPerRow++;
});
To deal with your 'edge' cases, you could do:
if(newIndex >= $(".test").length) {
newIndex = $(".test").length - newIndex;
}
moveUp: function () {
var that = this;
var index = $(this).index();
var containerWidth = parseInt( $('.select-icon-list').innerWidth(), 10);
var iconWidth = parseInt( $('.select-icon-list > a').width(), 10);
var noOfCols = Math.floor( containerWidth / iconWidth );
var newIndex = ( (index - noOfCols) < 0 ) ? index : (index - noOfCols);
var elem = $('.select-icon-list > a')[index];
},
Cache what ever remains static.
How can I stop the autoplay function of cSlider with an onmouseover event?
HTML:
<div id="da-slider" class="da-slider">
<div class="da-slide">
<p>Text</p>
</div>
<div class="da-slide">
<p>More text</p>
</div>
</div>
What I have tried so far with jQuery:
$(function() {
$('#da-slider').cslider({
autoplay : true,
bgincrement : 450
});
});
$('#da-slider').hover(function() {
if($('#daslider').autoplay('true')){
autoplay: false
}
}, function () {
autoplay: true
});
This is the one I'm using:
http://tympanus.net/codrops/2012/03/15/parallax-content-slider-with-css3-and-jquery/
This feature not implemented by default but this shouldn't stop you from implementing it on your own. Look at modified plugin code below (draw attention on stop and 'start' methods)
(function ($, undefined) {
/*
* Slider object.
*/
$.Slider = function (options, element) {
this.$el = $(element);
this._init(options);
};
$.Slider.defaults = {
current: 0, // index of current slide
bgincrement: 50, // increment the bg position (parallax effect) when sliding
autoplay: false, // slideshow on / off
interval: 4000 // time between transitions
};
$.Slider.prototype = {
_init: function (options) {
this.options = $.extend(true, {}, $.Slider.defaults, options);
this.$slides = this.$el.children('div.da-slide');
this.slidesCount = this.$slides.length;
this.current = this.options.current;
if (this.current < 0 || this.current >= this.slidesCount) {
this.current = 0;
}
this.$slides.eq(this.current).addClass('da-slide-current');
var $navigation = $('<nav class="da-dots"/>');
for (var i = 0; i < this.slidesCount; ++i) {
$navigation.append('<span/>');
}
$navigation.appendTo(this.$el);
this.$pages = this.$el.find('nav.da-dots > span');
this.$navNext = this.$el.find('span.da-arrows-next');
this.$navPrev = this.$el.find('span.da-arrows-prev');
this.isAnimating = false;
this.bgpositer = 0;
this.cssAnimations = Modernizr.cssanimations;
this.cssTransitions = Modernizr.csstransitions;
if (!this.cssAnimations || !this.cssAnimations) {
this.$el.addClass('da-slider-fb');
}
this._updatePage();
// load the events
this._loadEvents();
// slideshow
if (this.options.autoplay) {
this._startSlideshow();
}
},
_navigate: function (page, dir) {
var $current = this.$slides.eq(this.current), $next, _self = this;
if (this.current === page || this.isAnimating) return false;
this.isAnimating = true;
// check dir
var classTo, classFrom, d;
if (!dir) {
(page > this.current) ? d = 'next' : d = 'prev';
}
else {
d = dir;
}
if (this.cssAnimations && this.cssAnimations) {
if (d === 'next') {
classTo = 'da-slide-toleft';
classFrom = 'da-slide-fromright';
++this.bgpositer;
}
else {
classTo = 'da-slide-toright';
classFrom = 'da-slide-fromleft';
--this.bgpositer;
}
this.$el.css('background-position', this.bgpositer * this.options.bgincrement + '% 0%');
}
this.current = page;
$next = this.$slides.eq(this.current);
if (this.cssAnimations && this.cssAnimations) {
var rmClasses = 'da-slide-toleft da-slide-toright da-slide-fromleft da-slide-fromright';
$current.removeClass(rmClasses);
$next.removeClass(rmClasses);
$current.addClass(classTo);
$next.addClass(classFrom);
$current.removeClass('da-slide-current');
$next.addClass('da-slide-current');
}
// fallback
if (!this.cssAnimations || !this.cssAnimations) {
$next.css('left', (d === 'next') ? '100%' : '-100%').stop().animate({
left: '0%'
}, 1000, function () {
_self.isAnimating = false;
});
$current.stop().animate({
left: (d === 'next') ? '-100%' : '100%'
}, 1000, function () {
$current.removeClass('da-slide-current');
});
}
this._updatePage();
},
_updatePage: function () {
this.$pages.removeClass('da-dots-current');
this.$pages.eq(this.current).addClass('da-dots-current');
},
_startSlideshow: function () {
var _self = this;
this.slideshow = setTimeout(function () {
var page = (_self.current < _self.slidesCount - 1) ? page = _self.current + 1 : page = 0;
_self._navigate(page, 'next');
if (_self.options.autoplay) {
_self._startSlideshow();
}
}, this.options.interval);
},
page: function (idx) {
if (idx >= this.slidesCount || idx < 0) {
return false;
}
if (this.options.autoplay) {
clearTimeout(this.slideshow);
this.options.autoplay = false;
}
this._navigate(idx);
},
stop: function () {
if (this.options.autoplay) {
clearTimeout(this.slideshow);
this.options.autoplay = false;
}
},
start: function () {
this.options.autoplay = true;
this._startSlideshow();
},
_loadEvents: function () {
var _self = this;
this.$pages.on('click.cslider', function (event) {
_self.page($(this).index());
return false;
});
this.$navNext.on('click.cslider', function (event) {
if (_self.options.autoplay) {
clearTimeout(_self.slideshow);
_self.options.autoplay = false;
}
var page = (_self.current < _self.slidesCount - 1) ? page = _self.current + 1 : page = 0;
_self._navigate(page, 'next');
return false;
});
this.$navPrev.on('click.cslider', function (event) {
if (_self.options.autoplay) {
clearTimeout(_self.slideshow);
_self.options.autoplay = false;
}
var page = (_self.current > 0) ? page = _self.current - 1 : page = _self.slidesCount - 1;
_self._navigate(page, 'prev');
return false;
});
if (this.cssTransitions) {
if (!this.options.bgincrement) {
this.$el.on('webkitAnimationEnd.cslider animationend.cslider OAnimationEnd.cslider', function (event) {
if (event.originalEvent.animationName === 'toRightAnim4' || event.originalEvent.animationName === 'toLeftAnim4') {
_self.isAnimating = false;
}
});
}
else {
this.$el.on('webkitTransitionEnd.cslider transitionend.cslider OTransitionEnd.cslider', function (event) {
if (event.target.id === _self.$el.attr('id'))
_self.isAnimating = false;
});
}
}
}
};
var logError = function (message) {
if (this.console) {
console.error(message);
}
};
$.fn.cslider = function (options) {
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
var instance = $.data(this, 'cslider');
if (!instance) {
logError("cannot call methods on cslider prior to initialization; " +
"attempted to call method '" + options + "'");
return;
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
logError("no such method '" + options + "' for cslider instance");
return;
}
instance[options].apply(instance, args);
});
}
else {
this.each(function () {
var instance = $.data(this, 'cslider');
if (!instance) {
$.data(this, 'cslider', new $.Slider(options, this));
}
});
}
return this;
};
})(jQuery);
With updated plugin you can pause and renew autiplaying with this code:
$('#da-slider').hover(
function () {
$(this).cslider("stop");
},
function () {
$(this).cslider("start");
}
);
I am trying to render a pdf in chrome using PDFJS
This is the function I am calling:
open: function pdfViewOpen(url, scale, password) {
var parameters = {password: password};
if (typeof url === 'string') { // URL
this.setTitleUsingUrl(url);
parameters.url = url;
} else if (url && 'byteLength' in url) { // ArrayBuffer
parameters.data = url;
}
if (!PDFView.loadingBar) {
PDFView.loadingBar = new ProgressBar('#loadingBar', {});
}
this.pdfDocument = null;
var self = this;
self.loading = true;
getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
},
function getDocumentError(message, exception) {
if (exception && exception.name === 'PasswordException') {
if (exception.code === 'needpassword') {
var promptString = mozL10n.get('request_password', null,
'PDF is protected by a password:');
password = prompt(promptString);
if (password && password.length > 0) {
return PDFView.open(url, scale, password);
}
}
}
var loadingErrorMessage = mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.');
if (exception && exception.name === 'InvalidPDFException') {
// change error message also for other builds
var loadingErrorMessage = mozL10n.get('invalid_file_error', null,
'Invalid or corrupted PDF file.');
//#if B2G
// window.alert(loadingErrorMessage);
// return window.close();
//#endif
}
var loadingIndicator = document.getElementById('loading');
loadingIndicator.textContent = mozL10n.get('loading_error_indicator',
null, 'Error');
var moreInfo = {
message: message
};
self.error(loadingErrorMessage, moreInfo);
self.loading = false;
},
function getDocumentProgress(progressData) {
self.progress(progressData.loaded / progressData.total);
}
);
}
This is the call:
PDFView.open('/MyPDFs/Pdf2.pdf', 'auto', null);
All I get is this:
If you notice, even the page number is retrieved but the content is not painted in the pages. Can´t find why.. Is the any other function I should call next to PDFView.open?
Found the solution...!
This is the code that does the work.
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call!
Thanks