Redactor: dropdown plugin - javascript

I try to implement a colorpicker-fontcolor plugin to redactor-js.
http://jsfiddle.net/ped7txq6/
$(function(){
//plugin
$.Redactor.prototype.fontcolor = function()
{
return {
init: function()
{
var name = 'fontcolor';
var rdctr = this;
var button = this.button.addAfter('fontsize', name, this.lang.get(name));
var $dropdown = this.button.addDropdown(button);
$dropdown.css('min-width', '199px');
this.fontcolor.buildPicker($dropdown, name);
button.on('click', function(){
rdctr.selection.save();
});
},
buildPicker: function($dropdown, name)
{
var rdctr = this;
var $picker = $('<p>').ColorPicker({
flat: true,
onSubmit: function(hsb, hex, rgb, el){
// $(el).val('#' + hex);
// $(el).ColorPickerHide();
},
onChange: function(hsb, hex, rgb, el){
// $(el).val(hex);
rdctr.fontcolor.set('color', '#' + hex);
}
}).bind('keyup', function(){
//$(rdctr).ColorPickerSetColor(rdctr.value);
// rdctr.fontcolor.set('color', '#' + hex);
});
$dropdown.append($picker);
},
set: function(rule, type)
{
console.log('_', type);
//selected color
this.selection.restore();
this.inline.format('span', 'style', rule + ':' + type + ';');
},
remove: function(rule)
{
//removed color
// this.inline.removeStyleRule(rule);
}
};
};
//editor
$('#redactor').redactor({
plugins: ['fontcolor'],
focus: true,
changeCallback: function()
{
},
blurCallback: function()
{
}
});
});
I have two problem:
When I clicked in the dropdown on the colorpicker, the dropdown is close,
Sometimes when I selected the color, the text in the editor get the default color, not actual color from colorpicker.
Anyone can help in these?
Thanks a lot!

Check the font color plugin for Redactor

Related

Dynamically change start value for range sliders

I'm using two range sliders on a page and I want these two to be dependent of each other.
My second slider should never be able to contain a lower value than my first slider, it should start from what's being selected on the first slider.
I've tried to to change myself,
Here is what I have so far: https://codepen.io/anon/pen/xrOQeM
$(document).ready(function () {
var input1 = $("input").val();
console.log(input1);
var input2 = $("#second");
$("#second").attr("min",input1);
alert(input2);
});
Put this inside your js file. It should work. or follow this example.
https://codepen.io/ayang10/pen/BZzEWZ
var valueBubble = '<output class="rangeslider__value-bubble" />';
var rangeSlider1 = $('#first');
var rangeSlider2 = $('#second');
function updateValueBubble(pos, value, context) {
pos = pos || context.position;
value = value || context.value;
var $valueBubble = $('.rangeslider__value-bubble', context.$range);
var tempPosition = pos + context.grabPos;
var position = (tempPosition <= context.handleDimension) ? context.handleDimension : (tempPosition >= context.maxHandlePos) ? context.maxHandlePos : tempPosition;
if ($valueBubble.length) {
$valueBubble[0].style.left = Math.ceil(position) + 'px';
$valueBubble[0].innerHTML = value;
}
}
rangeSlider1
.rangeslider({
polyfill: false,
onInit: function() {
this.$range.append($(valueBubble));
updateValueBubble(null, null, this);
},
onSlide: function(pos, value) {
updateValueBubble(pos, value, this);
}
})
.on('input', function() {
rangeSlider2[0].value = this.value;
});
rangeSlider2
.rangeslider({
polyfill: false,
onInit: function() {
this.$range.append($(valueBubble));
updateValueBubble(null, null, this);
},
onSlide: function(pos, value) {
updateValueBubble(pos, value, this);
}
})
rangeSlider1.on('input', function() {
rangeSlider2.attr("min", this.value);
rangeSlider2.rangeslider('update', true);
});

Shortcode dropdown box in Tinymce is not working in WordPress 3.9?

Hi since the new version is about to be released I thought I would download it and see if my theme works still.
Everything works great apart from the dropdown box which is now longer showing.
Here is the codes we used to show it in previous versions.
PHP CODE:
function register_ppp_shortcodes( $buttons ) {
array_unshift( $buttons, "Shortcodes" );
return $buttons;
}
function add_ppp_shortcodes( $plugin_array ) {
$plugin_array['Shortcodes'] = get_template_directory_uri() . '/js/Shortcodes_js.js';
return $plugin_array;
}
function ppp_shortcodes() {
if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
return;
}
if ( get_user_option('rich_editing') == 'true' ) {
add_filter( 'mce_external_plugins', 'add_ppp_shortcodes' );
add_filter( 'mce_buttons', 'register_ppp_shortcodes' );
}
}
add_action('init', 'ppp_shortcodes');
JS CODE:
/*global tinyMCE, tinymce*/
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, maxerr:50 */
(function() {
"use strict";
tinymce.create('tinymce.plugins.Shortcodes', {
init : function(ed, url) {
ed = ed;
url = url;
},
createControl : function(n, cm) {
if(n==='Shortcodes'){
var mtb = cm.createListBox('Shortcodes', {
title : 'Shortcodes',
onselect : function(p) {
var selected = false;
var content = '';
switch (p){
case 'H1 Title':{
var h1titleclass = prompt("Would you like a custom class?", "");
selected = tinyMCE.activeEditor.selection.getContent();
if(h1titleclass != ''){
h1titleclass = 'class= "'+h1titleclass+'"';
}
if (selected) {
content = '[h1'+h1titleclass+']' + selected + '[/h1]';
} else {
content = '[h1'+h1titleclass+'][/h1]';
}
tinymce.execCommand('mceInsertContent', false, content);
} // finished shortcode
break;
case 'H2 Title':{
var h2titleclass = prompt("Would you like a custom class?", "");
selected = tinyMCE.activeEditor.selection.getContent();
if(h2titleclass != ''){
h2titleclass = 'class= "'+h2titleclass+'"';
}
if (selected) {
content = '[h2'+h2titleclass+']' + selected + '[/h2]';
} else {
content = '[h2'+h2titleclass+'][/h2]';
}
tinymce.execCommand('mceInsertContent', false, content);
} // finished shortcode
break;
}
}
});
// Add some menu items
var my_shortcodes = ['H1 Title','H2 Title'];
for(var i in my_shortcodes){
if (true) {mtb.add(my_shortcodes[i],my_shortcodes[i]);}
}
return mtb;
}
return null;
}
});
tinymce.PluginManager.add('Shortcodes', tinymce.plugins.Shortcodes);
})();
Can anyone point me in the right direction on where to start.
I know very little about tinymce as you can tell :(
Thanks
In tinymce4 createControl doen't exist anymore.
You will have to create a button and assign text-value pairs as values to that button.
Use the onSelect function to do stuff when you choose an elemtn from the dropdow list.
Here is a piece of example code:
var my_options = [];
my_options.push({text: "title1", value: "value1"});
my_options.push({text: "title2", value: "value2"});
my_options.push({text: "title3", value: "value3"});
ed.addButton('shortcodes', {
type: 'listbox',
text: 'my_own_decription',
icon: false,
tooltip: 'my_own_decription',
fixedWidth: true,
onselect: function(e)
{
var options = {paragraphs: 1, calldirect: 1};
var text = this.text();
var value = this.value();
console.log("Text choosen:", text);
console.log("Value choosen:", value);
// get selection and range
var selection = ed.selection;
var rng = selection.getRng();
...
ed.focus();
},
values: my_options,
onPostRender: function()
{
ed.my_control = this; // ui control element
}
});
I had the same issue and was searching around the web. The best possible solution I've found was this article.
It worked for me like a charm.
(function() {
"use strict";
tinymce.create('tinymce.plugins.shortcodes', {
init : function(ed, url) {
ed.addButton( 'shortcodes', {
type: 'listbox',
text: 'My Shortcodes',
icon: false,
onselect: function(e) {
},
values: [
{text: 'H1 Title', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[h1][/h1]');
}},
{text: 'H2 Title', onclick : function() {
var selected2 = false;
var content2 = selected2 = tinyMCE.activeEditor.selection.getContent();
var h2titleclass = prompt("Would you like a custom class?", "");
if(h2titleclass != ''){
h2titleclass = ' class= "'+h2titleclass+'"';
}
if (selected2 !== '') {
content2 = '[h2'+h2titleclass+']' + selected2 + '[/h2]';
} else {
content2 = '[h2'+h2titleclass+'][/h2]';
}
tinymce.execCommand('mceInsertContent', false, content2);
}},
]
});
},
});
tinymce.PluginManager.add('shortcodes', tinymce.plugins.shortcodes);
})()

How to avoid getting same functionality by jquery in same multiple elements?

I've very little knowledge at jQuery. I'm working at a webpage. There are different kinds of select option element at that page. Among one of them, I've to use a jQuery Dropdown checkbox. This one, I've used.
I can implement this at my webpage successfully. But, problem is it affects all my Select option element!! I've different class name for different select element. like
<select name="company" class="company">
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
</select>
<select name="institute" class="institute">
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
</select>
<select name="group" class="dropdownCheckbox">
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
<option> Company Name </option>
</select>
I've used the jquery at last one(class="dropdownCheckbox"). But, it affected all the select element. I can't understand how I edit the jquery defining only for class="dropdownCheckbox".
This is the javascript code for HTML file:
<script type="text/javascript">
$(function(){
$("select").multiselect();
});
</script>
And the main javasript file for the effect(jquery.multiselect.js):
(function($, undefined) {
var multiselectID = 0;
var $doc = $(document);
$.widget("ech.multiselect.dropdownCheckbox", {
// default options
options: {
header: true,
height: 175,
minWidth: 310,
classes: 'dropdownCheckbox',
checkAllText: 'Check all',
uncheckAllText: 'Uncheck all',
noneSelectedText: 'Select Group',
selectedText: 'Select Group',
selectedList: 0,
show: null,
hide: null,
autoOpen: false,
multiple: true,
position: {},
appendTo: "body"
},
_create: function() {
var el = this.element.hide();
var o = this.options;
this.speed = $.fx.speeds._default; // default speed for effects
this._isOpen = false; // assume no
// create a unique namespace for events that the widget
// factory cannot unbind automatically. Use eventNamespace if on
// jQuery UI 1.9+, and otherwise fallback to a custom string.
this._namespaceID = this.eventNamespace || ('multiselect' + multiselectID);
var button = (this.button = $('<button type="button"><span class="ui-icon ui-icon-triangle-1-s"></span></button>'))
.addClass('ui-multiselect ui-widget ui-state-default ui-corner-all')
.addClass(o.classes)
.attr({ 'title':el.attr('title'), 'aria-haspopup':true, 'tabIndex':el.attr('tabIndex') })
.insertAfter(el),
buttonlabel = (this.buttonlabel = $('<span />'))
.html(o.noneSelectedText)
.appendTo(button),
menu = (this.menu = $('<div />'))
.addClass('ui-multiselect-menu ui-widget ui-widget-content ui-corner-all')
.addClass(o.classes)
.appendTo($(o.appendTo)),
header = (this.header = $('<div />'))
.addClass('ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix')
.appendTo(menu),
headerLinkContainer = (this.headerLinkContainer = $('<ul />'))
.addClass('ui-helper-reset')
.html(function() {
if(o.header === true) {
return '<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>' + o.checkAllText + '</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>' + o.uncheckAllText + '</span></a></li>';
} else if(typeof o.header === "string") {
return '<li>' + o.header + '</li>';
} else {
return '';
}
})
.append('<li class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></li>')
.appendTo(header),
checkboxContainer = (this.checkboxContainer = $('<ul />'))
.addClass('ui-multiselect-checkboxes ui-helper-reset')
.appendTo(menu);
// perform event bindings
this._bindEvents();
// build menu
this.refresh(true);
// some addl. logic for single selects
if(!o.multiple) {
menu.addClass('ui-multiselect-single');
}
// bump unique ID
multiselectID++;
},
_init: function() {
if(this.options.header === false) {
this.header.hide();
}
if(!this.options.multiple) {
this.headerLinkContainer.find('.ui-multiselect-all, .ui-multiselect-none').hide();
}
if(this.options.autoOpen) {
this.open();
}
if(this.element.is(':disabled')) {
this.disable();
}
},
refresh: function(init) {
var el = this.element;
var o = this.options;
var menu = this.menu;
var checkboxContainer = this.checkboxContainer;
var optgroups = [];
var html = "";
var id = el.attr('id') || multiselectID++; // unique ID for the label & option tags
// build items
el.find('option').each(function(i) {
var $this = $(this);
var parent = this.parentNode;
var description = this.innerHTML;
var title = this.title;
var value = this.value;
var inputID = 'ui-multiselect-' + (this.id || id + '-option-' + i);
var isDisabled = this.disabled;
var isSelected = this.selected;
var labelClasses = [ 'ui-corner-all' ];
var liClasses = (isDisabled ? 'ui-multiselect-disabled ' : ' ') + this.className;
var optLabel;
// is this an optgroup?
if(parent.tagName === 'OPTGROUP') {
optLabel = parent.getAttribute('label');
// has this optgroup been added already?
if($.inArray(optLabel, optgroups) === -1) {
html += '<li class="ui-multiselect-optgroup-label ' + parent.className + '">' + optLabel + '</li>';
optgroups.push(optLabel);
}
}
if(isDisabled) {
labelClasses.push('ui-state-disabled');
}
// browsers automatically select the first option
// by default with single selects
if(isSelected && !o.multiple) {
labelClasses.push('ui-state-active');
}
html += '<li class="' + liClasses + '">';
// create the label
html += '<label for="' + inputID + '" title="' + title + '" class="' + labelClasses.join(' ') + '">';
html += '<input id="' + inputID + '" name="multiselect_' + id + '" type="' + (o.multiple ? "checkbox" : "radio") + '" value="' + value + '" title="' + title + '"';
// pre-selected?
if(isSelected) {
html += ' checked="checked"';
html += ' aria-selected="true"';
}
// disabled?
if(isDisabled) {
html += ' disabled="disabled"';
html += ' aria-disabled="true"';
}
// add the title and close everything off
html += ' /><span>' + description + '</span></label></li>';
});
// insert into the DOM
checkboxContainer.html(html);
// cache some moar useful elements
this.labels = menu.find('label');
this.inputs = this.labels.children('input');
// set widths
this._setButtonWidth();
this._setMenuWidth();
// remember default value
this.button[0].defaultValue = this.update();
// broadcast refresh event; useful for widgets
if(!init) {
this._trigger('refresh');
}
},
// updates the button text. call refresh() to rebuild
update: function() {
var o = this.options;
var $inputs = this.inputs;
var $checked = $inputs.filter(':checked');
var numChecked = $checked.length;
var value;
if(numChecked === 0) {
value = o.noneSelectedText;
} else {
if($.isFunction(o.selectedText)) {
value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
} else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
value = $checked.map(function() { return $(this).next().html(); }).get().join(', ');
} else {
value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
}
}
this._setButtonValue(value);
return value;
},
// this exists as a separate method so that the developer
// can easily override it.
_setButtonValue: function(value) {
this.buttonlabel.text(value);
},
// binds events
_bindEvents: function() {
var self = this;
var button = this.button;
function clickHandler() {
self[ self._isOpen ? 'close' : 'open' ]();
return false;
}
// webkit doesn't like it when you click on the span :(
button
.find('span')
.bind('click.multiselect', clickHandler);
// button events
button.bind({
click: clickHandler,
keypress: function(e) {
switch(e.which) {
case 27: // esc
case 38: // up
case 37: // left
self.close();
break;
case 39: // right
case 40: // down
self.open();
break;
}
},
mouseenter: function() {
if(!button.hasClass('ui-state-disabled')) {
$(this).addClass('ui-state-hover');
}
},
mouseleave: function() {
$(this).removeClass('ui-state-hover');
},
focus: function() {
if(!button.hasClass('ui-state-disabled')) {
$(this).addClass('ui-state-focus');
}
},
blur: function() {
$(this).removeClass('ui-state-focus');
}
});
// header links
this.header.delegate('a', 'click.multiselect', function(e) {
// close link
if($(this).hasClass('ui-multiselect-close')) {
self.close();
// check all / uncheck all
} else {
self[$(this).hasClass('ui-multiselect-all') ? 'checkAll' : 'uncheckAll']();
}
e.preventDefault();
});
// optgroup label toggle support
this.menu.delegate('li.ui-multiselect-optgroup-label a', 'click.multiselect', function(e) {
e.preventDefault();
var $this = $(this);
var $inputs = $this.parent().nextUntil('li.ui-multiselect-optgroup-label').find('input:visible:not(:disabled)');
var nodes = $inputs.get();
var label = $this.parent().text();
// trigger event and bail if the return is false
if(self._trigger('beforeoptgrouptoggle', e, { inputs:nodes, label:label }) === false) {
return;
}
// toggle inputs
self._toggleChecked(
$inputs.filter(':checked').length !== $inputs.length,
$inputs
);
self._trigger('optgrouptoggle', e, {
inputs: nodes,
label: label,
checked: nodes[0].checked
});
})
.delegate('label', 'mouseenter.multiselect', function() {
if(!$(this).hasClass('ui-state-disabled')) {
self.labels.removeClass('ui-state-hover');
$(this).addClass('ui-state-hover').find('input').focus();
}
})
.delegate('label', 'keydown.multiselect', function(e) {
e.preventDefault();
switch(e.which) {
case 9: // tab
case 27: // esc
self.close();
break;
case 38: // up
case 40: // down
case 37: // left
case 39: // right
self._traverse(e.which, this);
break;
case 13: // enter
$(this).find('input')[0].click();
break;
}
})
.delegate('input[type="checkbox"], input[type="radio"]', 'click.multiselect', function(e) {
var $this = $(this);
var val = this.value;
var checked = this.checked;
var tags = self.element.find('option');
// bail if this input is disabled or the event is cancelled
if(this.disabled || self._trigger('click', e, { value: val, text: this.title, checked: checked }) === false) {
e.preventDefault();
return;
}
// make sure the input has focus. otherwise, the esc key
// won't close the menu after clicking an item.
$this.focus();
// toggle aria state
$this.attr('aria-selected', checked);
// change state on the original option tags
tags.each(function() {
if(this.value === val) {
this.selected = checked;
} else if(!self.options.multiple) {
this.selected = false;
}
});
// some additional single select-specific logic
if(!self.options.multiple) {
self.labels.removeClass('ui-state-active');
$this.closest('label').toggleClass('ui-state-active', checked);
// close menu
self.close();
}
// fire change on the select box
self.element.trigger("change");
// setTimeout is to fix multiselect issue #14 and #47. caused by jQuery issue #3827
// http://bugs.jquery.com/ticket/3827
setTimeout($.proxy(self.update, self), 10);
});
// close each widget when clicking on any other element/anywhere else on the page
$doc.bind('mousedown.' + this._namespaceID, function(event) {
var target = event.target;
if(self._isOpen
&& target !== self.button[0]
&& target !== self.menu[0]
&& !$.contains(self.menu[0], target)
&& !$.contains(self.button[0], target)
) {
self.close();
}
});
// deal with form resets. the problem here is that buttons aren't
// restored to their defaultValue prop on form reset, and the reset
// handler fires before the form is actually reset. delaying it a bit
// gives the form inputs time to clear.
$(this.element[0].form).bind('reset.multiselect', function() {
setTimeout($.proxy(self.refresh, self), 10);
});
},
// set button width
_setButtonWidth: function() {
var width = this.element.outerWidth();
var o = this.options;
if(/\d/.test(o.minWidth) && width < o.minWidth) {
width = o.minWidth;
}
// set widths
this.button.outerWidth(width);
},
// set menu width
_setMenuWidth: function() {
var m = this.menu;
m.outerWidth(this.button.outerWidth());
},
// move up or down within the menu
_traverse: function(which, start) {
var $start = $(start);
var moveToLast = which === 38 || which === 37;
// select the first li that isn't an optgroup label / disabled
var $next = $start.parent()[moveToLast ? 'prevAll' : 'nextAll']('li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)').first();
// if at the first/last element
if(!$next.length) {
var $container = this.menu.find('ul').last();
// move to the first/last
this.menu.find('label')[ moveToLast ? 'last' : 'first' ]().trigger('mouseover');
// set scroll position
$container.scrollTop(moveToLast ? $container.height() : 0);
} else {
$next.find('label').trigger('mouseover');
}
},
// This is an internal function to toggle the checked property and
// other related attributes of a checkbox.
//
// The context of this function should be a checkbox; do not proxy it.
_toggleState: function(prop, flag) {
return function() {
if(!this.disabled) {
this[ prop ] = flag;
}
if(flag) {
this.setAttribute('aria-selected', true);
} else {
this.removeAttribute('aria-selected');
}
};
},
_toggleChecked: function(flag, group) {
var $inputs = (group && group.length) ? group : this.inputs;
var self = this;
// toggle state on inputs
$inputs.each(this._toggleState('checked', flag));
// give the first input focus
$inputs.eq(0).focus();
// update button text
this.update();
// gather an array of the values that actually changed
var values = $inputs.map(function() {
return this.value;
}).get();
// toggle state on original option tags
this.element
.find('option')
.each(function() {
if(!this.disabled && $.inArray(this.value, values) > -1) {
self._toggleState('selected', flag).call(this);
}
});
// trigger the change event on the select
if($inputs.length) {
this.element.trigger("change");
}
},
_toggleDisabled: function(flag) {
this.button.attr({ 'disabled':flag, 'aria-disabled':flag })[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
var inputs = this.menu.find('input');
var key = "ech-multiselect-disabled";
if(flag) {
// remember which elements this widget disabled (not pre-disabled)
// elements, so that they can be restored if the widget is re-enabled.
inputs = inputs.filter(':enabled').data(key, true)
} else {
inputs = inputs.filter(function() {
return $.data(this, key) === true;
}).removeData(key);
}
inputs
.attr({ 'disabled':flag, 'arial-disabled':flag })
.parent()[ flag ? 'addClass' : 'removeClass' ]('ui-state-disabled');
this.element.attr({
'disabled':flag,
'aria-disabled':flag
});
},
// open the menu
open: function(e) {
var self = this;
var button = this.button;
var menu = this.menu;
var speed = this.speed;
var o = this.options;
var args = [];
// bail if the multiselectopen event returns false, this widget is disabled, or is already open
if(this._trigger('beforeopen') === false || button.hasClass('ui-state-disabled') || this._isOpen) {
return;
}
var $container = menu.find('ul').last();
var effect = o.show;
// figure out opening effects/speeds
if($.isArray(o.show)) {
effect = o.show[0];
speed = o.show[1] || self.speed;
}
// if there's an effect, assume jQuery UI is in use
// build the arguments to pass to show()
if(effect) {
args = [ effect, speed ];
}
// set the scroll of the checkbox container
$container.scrollTop(0).height(o.height);
// positon
this.position();
// show the menu, maybe with a speed/effect combo
$.fn.show.apply(menu, args);
// select the first not disabled option
// triggering both mouseover and mouseover because 1.4.2+ has a bug where triggering mouseover
// will actually trigger mouseenter. the mouseenter trigger is there for when it's eventually fixed
this.labels.filter(':not(.ui-state-disabled)').eq(0).trigger('mouseover').trigger('mouseenter').find('input').trigger('focus');
button.addClass('ui-state-active');
this._isOpen = true;
this._trigger('open');
},
// close the menu
close: function() {
if(this._trigger('beforeclose') === false) {
return;
}
var o = this.options;
var effect = o.hide;
var speed = this.speed;
var args = [];
// figure out opening effects/speeds
if($.isArray(o.hide)) {
effect = o.hide[0];
speed = o.hide[1] || this.speed;
}
if(effect) {
args = [ effect, speed ];
}
$.fn.hide.apply(this.menu, args);
this.button.removeClass('ui-state-active').trigger('blur').trigger('mouseleave');
this._isOpen = false;
this._trigger('close');
},
enable: function() {
this._toggleDisabled(false);
},
disable: function() {
this._toggleDisabled(true);
},
checkAll: function(e) {
this._toggleChecked(true);
this._trigger('checkAll');
},
uncheckAll: function() {
this._toggleChecked(false);
this._trigger('uncheckAll');
},
getChecked: function() {
return this.menu.find('input').filter(':checked');
},
destroy: function() {
// remove classes + data
$.Widget.prototype.destroy.call(this);
// unbind events
$doc.unbind(this._namespaceID);
this.button.remove();
this.menu.remove();
this.element.show();
return this;
},
isOpen: function() {
return this._isOpen;
},
widget: function() {
return this.menu;
},
getButton: function() {
return this.button;
},
position: function() {
var o = this.options;
// use the position utility if it exists and options are specifified
if($.ui.position && !$.isEmptyObject(o.position)) {
o.position.of = o.position.of || this.button;
this.menu
.show()
.position(o.position)
.hide();
// otherwise fallback to custom positioning
} else {
var pos = this.button.offset();
this.menu.css({
top: pos.top + this.button.outerHeight(),
left: pos.left
});
}
},
// react to option changes after initialization
_setOption: function(key, value) {
var menu = this.menu;
switch(key) {
case 'header':
menu.find('div.ui-multiselect-header')[value ? 'show' : 'hide']();
break;
case 'checkAllText':
menu.find('a.ui-multiselect-all span').eq(-1).text(value);
break;
case 'uncheckAllText':
menu.find('a.ui-multiselect-none span').eq(-1).text(value);
break;
case 'height':
menu.find('ul').last().height(parseInt(value, 10));
break;
case 'minWidth':
this.options[key] = parseInt(value, 10);
this._setButtonWidth();
this._setMenuWidth();
break;
case 'selectedText':
case 'selectedList':
case 'noneSelectedText':
this.options[key] = value; // these all needs to update immediately for the update() call
this.update();
break;
case 'classes':
menu.add(this.button).removeClass(this.options.classes).addClass(value);
break;
case 'multiple':
menu.toggleClass('ui-multiselect-single', !value);
this.options.multiple = value;
this.element[0].multiple = value;
this.refresh();
break;
case 'position':
this.position();
}
$.Widget.prototype._setOption.apply(this, arguments);
}
});
})(jQuery);
How can I make this jquery active only for class="dropdownCheckbox"?
you can use
$(".dropdownCheckbox").multiselect();
You can use the class selector
<script type="text/javascript">
$(function(){
$("select.company").multiselect();
// Targets the select with class="company"
});
</script>
jQuery uses the same selctors as CSS does :)

Need to access the ID of autocomplete comboBox in jquery

i want to retrive id of Combobox on key event(or on Change:) written below
try to see the CHANGE:function in below code and suggest some tips
i want to retrive id of Combobox on key event(or on Change:) written below
try to see the CHANGE:function in below code and suggest some tips
(function($) {
$.widget("ui.combobox", {
_create: function() {
var input, self = this, select = this.element.hide(), selected = select.children(":selected"), value = selected.val() ?
selected.text() : "", wrapper = this.wrapper =
$("<span>").addClass("ui-combobox").insertAfter(select);
input = $("<input>")
.appendTo(wrapper)
.val(value)
.addClass("ui-state-default ui-combobox-input")
.autocomplete({
delay: 0,
minLength: 0,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function() {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
// alert(text);
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function(event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
},
change: function(event, ui) {
// alert($(event.target)[0].id);
//alert($(this).attr('id'));
alert(event.target.id);
if (!ui.item) {
xT = $(this).val();
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function() {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
xT = $(this).val();
$(".selPnext").show();
// remove invalid value, as it didn't match anything
// $(this).val("");
// select.val("");
// input.data("autocomplete").term = "";
return false;
}
}
}
})
//.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-combobox-toggle")
.click(function() {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function() {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
}); })(jQuery); var xT; function myVal() {
return xT; } $(function() {
//$("#tryy").combobox();
//$("#country").combobox(); });
You can just assign an id to the combobox:
$("<input>").attr('id', 'something')
Then onChange:
$('#something').live('change', function(){
var id = $(this).val();
});

IE6-7 Javascript

I am using the "mimic igoogle tutorial with cookies" by James Padolsey
http://james.padolsey.com/tag/cookies/
I have encountered a problem with the way that IE6 & 7 interprets the javascript. I have found the problem but I have no way of working around it.
The following code is long but the problem is only in one small section
/*
* Script from NETTUTS.com [by James Padolsey] V.2 (ENHANCED, WITH COOKIES!!!)
* #requires jQuery($), jQuery UI & sortable/draggable UI modules & jQuery COOKIE plugin
*/
var iNettuts = {
jQuery : $,
settings : {
columns : '.column',
widgetSelector: '.widget',
handleSelector: '.widget-head',
contentSelector: '.widget-content',
/* If you don't want preferences to be saved change this value to false, otherwise change it to the name of the cookie: */
saveToCookie: false,
widgetDefault : {
movable: true,
removable: true,
collapsible: true,
editable: false,
colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
},
widgetIndividual : {
static: {
movable: false,
removable: true,
collapsible: true,
editable: false,
}
},
},
init : function () {
this.attachStylesheet('css/sortable.js.css');
this.sortWidgets();
this.addWidgetControls();
this.makeSortable();
},
getWidgetSettings : function (id) {
var $ = this.jQuery,
settings = this.settings;
return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
},
addWidgetControls : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
$(settings.widgetSelector, $(settings.columns)).each(function () {
var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
if (thisWidgetSettings.removable) {
$(' ').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function () {
if(confirm('This widget will be removed, ok?')) {
$(this).parents(settings.widgetSelector).animate({
opacity: 0
},function () {
$(this).slideUp(function () {
$(this).toggleClass('closed');
/* Save prefs to cookie: */
iNettuts.savePreferences();
});
});
}
return false;
}).appendTo($(settings.handleSelector, this));
}
if (thisWidgetSettings.editable) {
$('Edit').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).toggle(function () {
$(this).css({backgroundPosition: '-66px 0', width: '55px'})
.parents(settings.widgetSelector)
.find('.edit-box').show().find('input').focus();
return false;
},function () {
$(this).css({backgroundPosition: '', width: '20px'})
.parents(settings.widgetSelector)
.find('.edit-box').hide();
return false;
}).appendTo($(settings.handleSelector,this));
$('<div class="edit-box" style="display:none;"/>')
.append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
.append((function(){
var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
$(thisWidgetSettings.colorClasses).each(function () {
colorList += '<li class="' + this + '"/>';
});
return colorList + '</ul>';
})())
.append('</ul>')
.insertAfter($(settings.handleSelector,this));
}
if (thisWidgetSettings.collapsible) {
$(' ').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function(){
$(this).parents(settings.widgetSelector).toggleClass('collapsed');
/* Save prefs to cookie: */
iNettuts.savePreferences();
return false;
}).prependTo($(settings.handleSelector,this));
}
});
$('.edit-box').each(function () {
$('input',this).keyup(function () {
$(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );
iNettuts.savePreferences();
});
$('ul.colors li',this).click(function () {
var colorStylePattern = /\bcolor-[\w]{1,}\b/,
thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
if (thisWidgetColorClass) {
$(this).parents(settings.widgetSelector)
.removeClass(thisWidgetColorClass[0])
.addClass($(this).attr('class').match(colorStylePattern)[0]);
/* Save prefs to cookie: */
iNettuts.savePreferences();
}
return false;
});
});
},
attachStylesheet : function (href) {
var $ = this.jQuery;
return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
},
makeSortable : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
$sortableItems = (function () {
var notSortable = null;
$(settings.widgetSelector,$(settings.columns)).each(function (i) {
if (!iNettuts.getWidgetSettings(this.id).movable) {
if(!this.id) {
this.id = 'widget-no-id-' + i;
}
notSortable += '#' + this.id + ',';
}
});
return $('> li:not(' + notSortable + ')', settings.columns);
})();
$sortableItems.find(settings.handleSelector).css({
cursor: 'move'
}).mousedown(function (e) {
$sortableItems.css({width:''});
$(this).parent().css({
width: $(this).parent().width() + 'px'
});
}).mouseup(function () {
if(!$(this).parent().hasClass('dragging')) {
$(this).parent().css({width:''});
} else {
$(settings.columns).sortable('disable');
}
});
$(settings.columns).sortable({
items: $sortableItems,
connectWith: $(settings.columns),
handle: settings.handleSelector,
placeholder: 'widget-placeholder',
forcePlaceholderSize: true,
revert: 300,
delay: 100,
opacity: 0.8,
containment: 'document',
start: function (e,ui) {
$(ui.helper).addClass('dragging');
},
stop: function (e,ui) {
$(ui.item).css({width:''}).removeClass('dragging');
$(settings.columns).sortable('enable');
/* Save prefs to cookie: */
iNettuts.savePreferences();
}
});
},
savePreferences : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings,
cookieString = '';
if(!settings.saveToCookie) {return;}
/* Assemble the cookie string */
$(settings.columns).each(function(i){
cookieString += (i===0) ? '' : '|';
$(settings.widgetSelector,this).each(function(i){
cookieString += (i===0) ? '' : ';';
/* ID of widget: */
cookieString += $(this).attr('id') + ',';
/* Color of widget (color classes) */
cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
/* Title of widget (replaced used characters) */
cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
/* Collapsed/not collapsed widget? : */
cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed,' : 'not-collapsed,';
/* Closed/not closed widget? : */
cookieString += $(settings.handleSelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
});
});
$.cookie(settings.saveToCookie,cookieString,{
expires: 10
//path: '/'
});
},
sortWidgets : function () {
var iNettuts = this,
$ = this.jQuery,
settings = this.settings;
/* Read cookie: */
var cookie = $.cookie(settings.saveToCookie);
if(!settings.saveToCookie||!cookie) {
/* Get rid of loading gif and show columns: */
$('body').css({background:'#fff'});
$(settings.columns).css({visibility:'visible'});
return;
}
/* For each column */
$(settings.columns).each(function(i){
var thisColumn = $(this),
widgetData = cookie.split('|')[i].split(';');
$(widgetData).each(function(){
if(!this.length) {return;}
var thisWidgetData = this.split(','),
clonedWidget = $('#' + thisWidgetData[0]),
colorStylePattern = /\bcolor-[\w]{1,}\b/,
thisWidgetColorClass = $(clonedWidget).attr('class').match(colorStylePattern);
/* Add/Replace new colour class: */
if (thisWidgetColorClass) {
$(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
}
/* Add/replace new title (Bring back reserved characters): */
$(clonedWidget).find('h3:eq(0)').html(thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','));
/* Modify collapsed state if needed: */
if(thisWidgetData[3]==='collapsed') {
/* Set CSS styles so widget is in COLLAPSED state */
$(clonedWidget).addClass('collapsed');
}
/* Modify closed state if needed: */
if(thisWidgetData[4]==='closed') {
/* Set CSS styles so widget is in CLOSED state */
$(clonedWidget).addClass('closed');
}
$('#' + thisWidgetData[0]).remove();
$(thisColumn).append(clonedWidget);
});
});
/* All done, remove loading gif and show columns: */
$('body').css({background:'#fff'});
$(settings.columns).css({visibility:'visible'});
}
};
iNettuts.init();
If I leave this section blank
widgetIndividual : {
static: {
movable: false,
removable: true,
collapsible: true,
editable: false,
}
}
For example, like this
widgetIndividual : {
}
Then it works fine on all browsers, unfortunately I need to use the Individual Widget settings for my project.
IE6-7 throws out an error because of these guys "}", I have no idea why.
Remove the last comma in this object it will work.
widgetIndividual : {
static: {
movable: false,
removable: true,
collapsible: true,
editable: false
}
}

Categories

Resources