jquery vars get to an event - javascript

i have a little problem with vars on event. So i have a plugin whitch called another plugin and i want to get a jquery element from called plugin to main plugin... like this.
(function($) {
$.fn.meRadioCheck = function(options, callback) {
options = $.extend($.fn.meRadioCheck.defaults, options);
var plugin = this;
plugin.init = function() {
return this.each(function() {
var $this = $(this);
var $span = $('<span/>');
var name = $this.attr('name');
/* here some stuff... */
/* check for Events */
if (($._data(this, "events") == null)) {
/* Change Event an Element binden */
$this.bind("xonChange", function() {
options.CheckBox_onChange.call($this)
});
$this.on({
change: function() {
/* here some stuff... */
/* throw Change Event */
$this.trigger("xonChange");
},
});
};
});
}
return this.each(function() {
var $this = $(this);
var name = $this.attr('name');
if (options.checked != $this.prop('checked')) { $this.click(); }
if (options.disabled) { $this.prop('disabled', true) } else { $this.prop('disabled', false) }
});
};
// Standard-Optionen für das Plugin
$.fn.meRadioCheck.defaults = {
'checked': false, /* This Checkbox or Radio Button is checked */
'debug': false, /* Debug Modus für das Plugin ein od. ausschalten */
'disabled': false, /* This Checkbox or Radio Button is disabled */
'CheckBox_onChange': function(el) {},
'RadioButton_onChange': function(el) {}
}
})(jQuery);
(function($) {
$.panel = function(options, callback) {
$('input[type=checkbox], input[type=radio]').meRadioCheck({
CheckBox_onChange: function(el) {
/* some stuff here... */
window.console.debug('panel: ' + typeof(el) + ', onChange: ', [el])
}
});
}
})(jQuery);
i only get this in the console: panel: undefined, onChange: [undefined]
but i want to get the CheckBox or RadioButton. I hope someone can help me...
Thanks... and have a nice Weekend.

How about:
(function($) {
$.fn.meRadioCheck.defaults = {
'debug': false, /* debug-mode for plugin */
'checked': false, /* this checkbox or radio button is checked */
'disabled': false, /* this checkbox or radio button is disabled */
'CheckBox_onChange': null,
'RadioButton_onChange': null
};
$.fn.meRadioCheck = function(overrideOptions, callback) {
var plugin = this,
options = $.extend($.fn.meRadioCheck.defaults, overrideOptions);
return this.each(function() {
var $this = $(this),
name = $this.attr('name');
if ( !$this.data().meRadioCheckInitDone ) {
$this.on("change", function() {
if (typeof options.CheckBox_onChange === "function") {
options.CheckBox_onChange.call(this);
}
}).data("meRadioCheckInitDone", true);
}
$this.prop('checked', !!options.checked);
$this.prop('disabled', !!options.disabled);
});
};
})(jQuery);
Changes
Gotten rid of .init(), it did not seem to serve any purpose.
Used a .data() variable instead of calling an internal API function to check if initialization is through. Seems cleaner.
Gotten rid of the custom xonChange event - listening to change directly will work just as well if all you do is call another function from there.
Added a typeof check for the event callback.
Setting $this.prop() unconditionally seems cleaner than the if-then-else you do.
On a more general note, you seem to implement some sort of data binding. Maybe looking into a data binding framework like knockout.js is worth it.

Related

How to set fadeout or timeout to alert sucess & warning boxes in opencart 2.2?

I want to set timeout to alert boxes in opencart 2.2. It should disappear after some seconds. I was trying in this code, but didnt work out. Or is this possible if click anywhere in the page the popup should disappear? need help.
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.5'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
Thanks in advance.
alert is the class that opencart uses while displaying error or success message, go to catalog/view/javascript/common.js,
at the end of code add
setTimeout(function(){ $('.alert').fadeOut() }, 5000);
you can change the time parameter based on your requirement.

Magento Jquery Bootstrap and Prototype conflict? nav-tabs dont work

I use Magento 1.9.2.4 and the following Theme
https://github.com/webcomm/magento-boilerplate
The description of it is "HTML5 Twitter Bootstrap 3.1 Magento Boilerplate Template"
It works fine with everything else of "Bootstrap responsive".
My problem is, that all of the following on this Site did not work on my
Installation:
http://www.w3schools.com/bootstrap/bootstrap_tabs_pills.asp
And "did not work" means you can click on next tab but the border and highlighting and so on is still on the first tab.
Same thing on "nav-pills" of Bootstrap.
In this Boilerplate there is a Workaround for Bootstrap dropdown:
jQuery.noConflict();
;(function ($) {
'use strict';
function Site(settings) {
this.windowLoaded = false;
}
Site.prototype = {
constructor: Site,
start: function () {
var me = this;
$(window).load(function () {
me.windowLoaded = true;
});
this.attach();
},
attach: function () {
this.attachBootstrapPrototypeCompatibility();
this.attachMedia();
},
attachBootstrapPrototypeCompatibility: function () {
/*// Bootstrap and Prototype don't play nice, in the sense that
// prototype is a really wacky horrible library. It'll
// hard-code CSS to hide an element when a hide() event
// is fired. See http://stackoverflow.com/q/19139063
// To overcome this with dropdowns that are both
// toggle style and hover style, we'll add a CSS
// class which has "display: block !important"
$('*').on('show.bs.dropdown show.bs.collapse active nav-tabs.active', function (e) {
$(e.target).addClass('bs-prototype-override');
});
$('*').on('hidden.bs.collapse nav-tabs', function (e) {
$(e.target).removeClass('bs-prototype-override');
});*/
var isBootstrapEvent = false;
if (window.jQuery) {
var all = jQuery('*');
jQuery.each(['hide.bs.dropdown',
'hide.bs.collapse',
'hide.bs.modal',
'hide.bs.tooltip',
'hide.bs.popover',
'hide.bs.tab'], function (index, eventName) {
all.on(eventName, function (event) {
isBootstrapEvent = true;
});
});
}
var originalHide = Element.hide;
Element.addMethods({
hide: function (element) {
if (isBootstrapEvent) {
isBootstrapEvent = false;
return element;
}
return originalHide(element);
}
});
},
attachMedia: function () {
var $links = $('[data-toggle="media"]');
if (!$links.length) return;
// When somebody clicks on a link, slide the
// carousel to the slide which matches the
// image index and show the modal
$links.on('click', function (e) {
e.preventDefault();
var $link = $(this),
$modal = $($link.attr('href')),
$carousel = $modal.find('.carousel'),
index = parseInt($link.data('index'));
$carousel.carousel(index);
$modal.modal('show');
return false;
});
}
};
jQuery(document).ready(function ($) {
var site = new Site();
site.start();
});
})(jQuery);
I already asked on github with no response question on github
So the Dropdown of Bootstrap is working.
My Question am i doing anything wrong or am i missing something?
Why does the nav-tabs not work in here?
Adding the "'bower_components/bootstrap/js/tab.js'," tab.js to the gulpfile.js AND
adding the tab class to the script.js solved my Problem with Bootstrap Nav Pills and Tabs.
$('*').on('show.bs.dropdown show.bs. hide.bs.tab hidden.bs.tab', function(e) {
$(e.target).addClass('bs-prototype-override');
});
$('*').on('hidden.bs.collapse', function(e) {
$(e.target).removeClass('bs-prototype-override');
});
At the end the code looks just like this:
jQuery.noConflict();
;(function($) {
'use strict';
function Site(settings) {
this.windowLoaded = false;
}
Site.prototype = {
constructor: Site,
start: function() {
var me = this;
$(window).load(function() {
me.windowLoaded = true;
});
this.attach();
},
attach: function() {
this.attachBootstrapPrototypeCompatibility();
this.attachMedia();
},
attachBootstrapPrototypeCompatibility: function() {
// Bootstrap and Prototype don't play nice, in the sense that
// prototype is a really wacky horrible library. It'll
// hard-code CSS to hide an element when a hide() event
// is fired. See http://stackoverflow.com/q/19139063
// To overcome this with dropdowns that are both
// toggle style and hover style, we'll add a CSS
// class which has "display: block !important"
$('*').on('show.bs.dropdown show.bs. hide.bs.tab hidden.bs.tab', function(e) {
$(e.target).addClass('bs-prototype-override');
});
$('*').on('hidden.bs.collapse', function(e) {
$(e.target).removeClass('bs-prototype-override');
});
},
attachMedia: function() {
var $links = $('[data-toggle="media"]');
if ( ! $links.length) return;
// When somebody clicks on a link, slide the
// carousel to the slide which matches the
// image index and show the modal
$links.on('click', function(e) {
e.preventDefault();
var $link = $(this),
$modal = $($link.attr('href')),
$carousel = $modal.find('.carousel'),
index = parseInt($link.data('index'));
$carousel.carousel(index);
$modal.modal('show');
return false;
});
}
};
jQuery(document).ready(function($) {
var site = new Site();
site.start();
});
})(jQuery);

Change variable based on which element is clicked

It is possible to change variable inside function which is based on element is user clicks?
In my case this will fully work for one kind of menu but I need two fully identical menu
with one difference -
second click handler must load toggleDrawer with changed $sidebar to $navbar variable.
/*
Variables
*/
var $sidebar = $('#sidebar'),
$navbar = $('#navbar'),
drawerOpen = false,
/*
Functions
*/
closeDrawer = function() {
drawerOpen = false;
$body.css('overflow','').removeClass('sidebar-open');
$sidebar.removeClass('open');
$sidebar.animate({'right':'-50%'},{duration:300});
$(this).hide();
},
openDrawer = function() {
drawerOpen = true;
$body.addClass('sidebar-open').css('overflow','hidden');
$sidebar.addClass('open');
$sidebar.animate({'right':'0%'},{duration:300});
},
toggleDrawer = function() {
if (drawerOpen) {
closeDrawer();
}else{
openDrawer();
}
},
/*
Bind Events
*/
$document.on('click', '.drawer-toggle-sidebar', function(event){
toggleDrawer();
event.preventDefault();
});
$document.on('click', '.drawer-toggle-navbar', function(event){
toggleDrawer();
event.preventDefault();
});
To elaborate on the above comment, and show an example:
Here are your functions with passing in the element you wish to open/close:
/*
Functions
*/
closeDrawer = function(drawer) {
drawerOpen = false;
$body.css('overflow','').removeClass('sidebar-open');
drawer.removeClass('open');
drawer.animate({'right':'-50%'},{duration:300});
$(this).hide();
},
openDrawer = function(drawer) {
drawerOpen = true;
$body.addClass('sidebar-open').css('overflow','hidden');
drawer.addClass('open');
drawer.animate({'right':'0%'},{duration:300});
},
toggleDrawer = function(drawer) {
if (drawerOpen) {
closeDrawer(drawer);
}else{
openDrawer(drawer);
}
},
And your bind events:
/*
Bind Events
*/
$document.on('click', '.drawer-toggle-sidebar', function(event){
toggleDrawer(event.currentTarget);
event.preventDefault();
});
$document.on('click', '.drawer-toggle-navbar', function(event){
toggleDrawer(event.currentTarget);
event.preventDefault();
});
You could even combine the two on click events into one and just pass in the currentTarget.
I hope this helps.

Cannot select a dynamically added list item until it is clicked

I have written a small JQuery plugin that creates a dropdown box based on bootstrap. I have written it to where a data attribute supplies a url that produces the list items. After the ajax call, Jquery loops through the list items and inserts them into the dropdown menu. Here is what I do not understand, the plugin takes a div with the class of .combobox and appends the required html to make the combobox. It uses two functions, _create() and _listItems(). _create() actually adds the html and calls on _listItems() to make the ajax call and it returns the list items to be appended. Looks like this:
;(function ( $, window, document, undefined ) {
var Combobox = function(element,options) {
this.$element = $(element);
this.$options = $.extend({}, $.fn.combobox.defaults, options);
this.$html = {
input: $('<input type="text" placeholder="[SELECT]" />').addClass('form-control'),
button: $('<div id="test"/>').addClass('input-group-btn')
.append($('<button />')
.addClass('btn btn-default input-sm')
.append('<span class="caret"></span>'))
}
this.$list_type = this.$element.attr('data-type');
this.$url = this.$element.attr('data-url');
this.$defaultValue = this.$element.attr('data-default');
this._create();
this.$input = this.$element.find('input');
this.$button = this.$element.find('button');
this.$list = this.$element.find('ul')
this.$button.on('click',$.proxy(this._toggleList,this));
this.$element.on('click','li',$.proxy(this._itemClicked,this));
this.$element.on('mouseleave',$.proxy(this._toggleList,this));
if(this.$defaultValue) {
this.selectByValue(this.$defaultValue);
}
}
Combobox.prototype = {
constructor: Combobox,
_create: function() {
this.$element.addClass('input-group input-group-sm')
.append(this.$html.input)
.append(this._listItems())
.append(this.$html.button);
},
_itemClicked: function(e){
this.$selectedItem = $(e.target).parent();
this.$input.val(this.$selectedItem.text());
console.log(this.$element.find('[data-value="W"]'))
this._toggleList(e);
e.preventDefault();
},
_listItems: function() {
var list = $('<ul />').addClass('dropdown-menu');
$.ajax({
url: this.$url,
type: 'POST',
data: {opt: this.$list_type},
success:function(data){
$.each(data,function(key,text){
list.append($('<li class="listObjItem" data-value="'+text.id+'">'+text.value+'</li>'));
})
}
})
return list
},
selectedItem: function() {
var item = this.$selectedItem;
var data = {};
if (item) {
var txt = this.$selectedItem.text();
data = $.extend({ text: txt }, this.$selectedItem.data());
}
else {
data = { text: this.$input.val()};
}
return data;
},
selectByValue: function(value) {
var selector = '[data-value="'+value+'"]';
this.selectBySelector(selector);
},
selectBySelector: function (selector) {
var $item = this.$element.find(selector);
if (typeof $item[0] !== 'undefined') {
this.$selectedItem = $item;
this.$input.val(this.$selectedItem.text());
}
else {
this.$selectedItem = null;
}
},
enable: function () {
this.$input.removeAttr('disabled');
this.$button.children().removeClass('disabled');
this.$button.on('click',$.proxy(this._toggleList,this));
},
disable: function () {
this.$input.attr('disabled', true);
this.$button.children().addClass('disabled');
this.$button.off('click',$.proxy(this._toggleList,this));
},
_toggleList: function(e) {
if(e.type == 'mouseleave') {
if(this.$list.is(':hidden')) {
return false;
} else {
this.$list.hide();
}
} else {
this.$list.toggle();
e.preventDefault();
}
}
}
$.fn.combobox = function (option) {
return this.each(function () {
if (!$.data(this, 'combobox')) {
$.data(this, 'combobox',
new Combobox( this, option ));
}
});
};
$.fn.combobox.defaults = {};
$.fn.combobox.Constructor = Combobox;
})( jQuery, window, document );
The problem is that after the items are appended to the DOM, everything is selectable accept the list items. I currently have an .on() statement that binds the click event with the list item. To test this out I have used console.log(this.$element.find('[data-value="W"]') and it does not return an element, however if I place that same console log in the click callback of the list item it will return the element and it is selectable. Am I doing something wrong?
EDIT
I have pasted the entire plugin to save on confusion.

Click Function on jQuery plugin only allows for single click

I've created this simple plugin to add multiple animations on click but the problem is that once the object is clicked it can not repeat the animation by clicking again, i can't figure out why the added class is not removing itself after the click function is complete to allow it to be clicked again and repeat.. any suggestions?
(function($) {
$.fn.vivify = function(options) {
var defaults = {
animation: 'bounce',
};
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = $(this);
var animation = o.animation;
obj.bind("click", function() {
obj.addClass(o.animation);
obj.addClass('vivify');
}, function() {
obj.removeClass(o.animation);
});
})
}
})(jQuery);​
Here's a working example (I guess, because I don't know exactly what's the intended effect of your plugin):
http://jsfiddle.net/gabrieleromanato/Fmr9g/
obj.bind("click", function() {
obj.addClass(o.animation);
obj.addClass('vivify');
},
// this callback is not valid
function() {
obj.removeClass(o.animation);
});
because .bind() accept parameters like following:
.bind(eventName, [eventData], [callback])
Read about .bind()
To remove class you can do:
obj.bind("click", function() {
obj.addClass(o.animation);
obj.addClass('vivify');
// you can removeClass here
obj.removeClass(o.animation);
// but you need some delay
setTimeou(function() {
obj.removeClass(o.animation);
}, 5000);
});
To increase the timeout you can do following:
return this.each(function(index, val) {
var o = options;
var obj = $(this);
var animation = o.animation;
obj.bind("click", function() {
obj.addClass(o.animation);
obj.addClass('vivify');
}, index * 2000);
});

Categories

Resources