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.
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`m trying to understand jQuery plugins and how to reference objects within other functions. So, I have this:
(function($) {
var methods = {
init: function (options) {
return this.each(function () {
var defaults = {
var1 : 'variable1',
var2 : 'variable2'
};
this.settings = $.extend(defaults,options);
});
},
add: function () {
// Access settings object here...how??
alert(this.settings.var1); ????
}
};
jQuery.fn.pluginName = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this,arguments);
} else {
console.error('Method '+method+' does not exist in plugin. Plugin aborted.');
}
};
}(jQuery));
So, my question is, once I have initialised the plugin, how can I reference the settings object inside the 'add' function when the 'add' function is called?
Thank you very much for any assistance.
The problem is the context value of this.
(function($) {
var methods = {
init: function(options) {
return this.each(function() {
var defaults = {
var1: 'variable1',
var2: 'variable2'
};
//here this is the dom object not the wrapping jQuery object
this.settings = $.extend(defaults, options);
});
},
add: function() {
//here this is the jQuery object
return this.each(function() {
//here this is again the dom object
console.log(this.settings.var1);
})
}
};
jQuery.fn.pluginName = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
console.error('Method ' + method + ' does not exist in plugin. Plugin aborted.');
}
};
}(jQuery));
$('div').pluginName({
var1: 'x'
});
$('div').pluginName('add')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I would recommend using the data api instead of attaching the settings object directly to the dom element reference
One basic boilerplate that I use for plugins is
(function($) {
function PluginName(el, settings) {
//your initialization code goes here
this.$el = $(el);
this.settings = $.extend({}, jQuery.fn.pluginName.defaults, settings);
}
PluginName.prototype.add = function() {
console.log('add', this, arguments);
}
PluginName.prototype.result = function() {
console.log('result', this, arguments);
return 'result'
}
PluginName.prototype._add = function() {
console.log('not called');
}
jQuery.fn.pluginName = function(method) {
var result, args = arguments;
this.each(function() {
var $this = $(this),
data = $this.data('pluginName');
if (data) {
if (/^[^_]/.test(method) && typeof data[method] == 'function') {
result = data[method].apply(data, Array.prototype.slice.call(args, 1));
if (result !== undefined) {
return false;
}
} else {
throw new Error('Unable to find the method ' + method);
}
} else if (typeof method == 'object') {
data = new PluginName(this, method);
$this.data('pluginName', data);
} else {
throw new Error('Illegal arguments passed');
}
})
return result === undefined ? this : result;
};
jQuery.fn.pluginName.defaults = {
var1: 'variable1',
var2: 'variable2'
};
}(jQuery));
$('div').pluginName({
var1: 'x'
});
try {
$('div').pluginName('add', 3, 5)
} catch (e) {
console.log(e);
}
try {
$('div').pluginName('add2', 3, 5)
} catch (e) {
console.log(e);
}
try {
$('div').pluginName('_add', 3, 5)
} catch (e) {
console.log(e);
}
try {
var x = $('div').pluginName('result', 3, 5);
console.log(x)
} catch (e) {
console.log(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div></div>
<div></div>
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
I'm trying to understand what this modenizr code is doing so I can simplify it and convert it to a jquery call for my click event.
Here is the current modenizr code:
(function(window, document, undefined) {
var transformProp = window.Modernizr.prefixed('transform'),
transitionProp = window.Modernizr.prefixed('transition'),
transitionEnd = (function() {
var props = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
};
return props.hasOwnProperty(transitionProp) ? props[transitionProp] : false;
})(),
hasTT = transitionEnd && transitionProp && transitionProp;
var log = function(obj)
{
if (typeof window.console === 'object' && typeof window.console.log === 'function') {
window.console.log(obj);
}
};
window.App = (function()
{
var _init = false, app = { };
app.init = function()
{
if (_init) {
return;
}
_init = true;
app.win = $(window);
app.docEl = $(document.documentElement);
app.bodyEl = $(document.body);
app.docEl.addClass('js-ready js-' + (hasTT ? 'advanced' : 'basic'));
var menuLinkEl = $('#menu-link'),
menuEl = $('#menu'),
wrapEl = $('#wrap');
var closeMenu =function()
{
if (hasTT) {
menuEl.one(transitionEnd, function(e) {
app.docEl.removeClass('js-offcanvas');
});
} else {
app.docEl.removeClass('js-offcanvas');
}
app.docEl.removeClass('js-menu');
};
var openMenu = function()
{
app.docEl.addClass('js-offcanvas js-menu');
};
menuLinkEl.on('click', function(e)
{
if (app.docEl.hasClass('js-menu')) {
closeMenu();
} else {
openMenu();
}
e.preventDefault();
});
};
return app;
})();
})(window, window.document);
I've made an attempt to convert everything with the exception of the transform (hasTT) Will my conversion work and how do I transform the hasTT call?
My Attempt:
var appWin = $(window);
var appDocEl = $(document.documentElement);
appDocEl.addClass('js-ready js-' + (hasTT ? 'advanced' : 'basic'));
var menuLinkEl = $('#menu-link'),
menuEl = $('#menu'),
wrapEl = $('#wrap');
var closeMenu =function()
{
/* how do I determine hasTT ? */
if (hasTT) {
menuEl.one(transitionEnd, function(e) {
appDocEl.removeClass('js-offcanvas');
});
} else {
appDocEl.removeClass('js-offcanvas');
}
appDocEl.removeClass('js-menu');
};
var openMenu = function(){
appDocEl.addClass('js-offcanvas js-menu');
};
menuLinkEl.on('click', function(e){
if (appDocEl.hasClass('js-menu')) {
closeMenu();
}
else {
openMenu();
}
e.preventDefault();
});
I currently load it like so:
$(document).ready(function() {
loadMain();
});
function loadMain() {
Modernizr.load([
{
load: [
'http://localhost/js/main.js'
],
complete: function()
{
window.App.init();
}
}
]);
}
I have this jQuery-script that gives any image or object with tag data-retina="true" a retina-resolution-image or background-image.
But how do I remove the last part from the script so that this function will apply on every image, not just the one with the data-retina tag?
(function($) {
"use strict";
var retinaReplace = function(element, options) {
this.options = options;
var $el = $(element);
var is_image = $el.is('img');
var normal_url = is_image ? $el.attr('src') : $el.backgroundImageUrl();
var retina_url = this.options.generateUrl($el, normal_url);
$('<img/>').attr('src', retina_url).load(function() {
if (is_image) {
$el.attr('src', $(this).attr('src'));
} else {
$el.backgroundImageUrl($(this).attr('src'));
$el.backgroundSize($(this)[0].width, $(this)[0].height);
}
$el.attr('data-retina', 'complete');
});
}
retinaReplace.prototype = {
constructor: retinaReplace
}
$.fn.retinaReplace = function(option) {
if (getDevicePixelRatio() <= 1) { return this; }
return this.each(function() {
var $this = $(this);
var data = $this.data('retinaReplace');
var options = $.extend({}, $.fn.retinaReplace.defaults, $this.data(), typeof option == 'object' && option);
if (!data) { $this.data('retinaReplace', (data = new retinaReplace(this, options))); }
if (typeof option == 'string') { data[option](); }
});
}
$.fn.retinaReplace.defaults = {
suffix: '-x2',
generateUrl: function(element, url) {
var dot_index = url.lastIndexOf('.');
var extension = url.substr(dot_index + 1);
var file = url.substr(0, dot_index);
return file + this.suffix + '.' + extension;
}
}
$.fn.retinaReplace.Constructor = retinaReplace;
var getDevicePixelRatio = function() {
if (window.devicePixelRatio === undefined) { return 1; }
return window.devicePixelRatio;
}
$.fn.backgroundImageUrl = function(url) {
return url ? this.each(function () {
$(this).css("background-image", 'url("' + url + '")')
}) : $(this).css("background-image").replace(/url\(|\)|"|'/g, "");
}
$.fn.backgroundSize = function(retinaWidth, retinaHeight) {
var sizeValue = Math.floor(retinaWidth/2) + 'px ' + Math.floor(retinaHeight/2) + 'px';
$(this).css("background-size", sizeValue);
$(this).css("-webkit-background-size", sizeValue);
}
$(function(){
$("[data-retina='true']").retinaReplace();
});
})(window.jQuery);
how do I remove the last part from the script so that this function will apply on every image, not just the once with the data-retina-tag?
Change:
$(function(){
$("[data-retina='true']").retinaReplace();
});
To:
$(function(){
$("img").retinaReplace();
});