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

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 :)

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);
});

I want to add a loading png in LiveSearch

I am using a plugin for live search .. everything is working fine .. i just want to add a loading png that appear on start of ajax request and disappear on results ..
please help me to customize the code just to add class where form id="search-kb-form" .. and remove the class when results are completed.
<form id="search-kb-form" class="search-kb-form" method="get" action="<?php echo home_url('/'); ?>" autocomplete="off">
<div class="wrapper-kb-fields">
<input type="text" id="s" name="s" placeholder="Search what you’re looking for" title="* Please enter a search term!">
<input type="submit" class="submit-button-kb" value="">
</div>
<div id="search-error-container"></div>
</form>
This is the plugin code
jQuery.fn.liveSearch = function (conf) {
var config = jQuery.extend({
url: {'jquery-live-search-result': 'search-results.php?q='},
id: 'jquery-live-search',
duration: 400,
typeDelay: 200,
loadingClass: 'loading',
onSlideUp: function () {},
uptadePosition: false,
minLength: 0,
width: null
}, conf);
if (typeof(config.url) == "string") {
config.url = { 'jquery-live-search-result': config.url }
} else if (typeof(config.url) == "object") {
if (typeof(config.url.length) == "number") {
var urls = {}
for (var i = 0; i < config.url.length; i++) {
urls['jquery-live-search-result-' + i] = config.url[i];
}
config.url = urls;
}
}
var searchStatus = {};
var liveSearch = jQuery('#' + config.id);
var loadingRequestCounter = 0;
// Create live-search if it doesn't exist
if (!liveSearch.length) {
liveSearch = jQuery('<div id="' + config.id + '"></div>')
.appendTo(document.body)
.hide()
.slideUp(0);
for (key in config.url) {
liveSearch.append('<div id="' + key + '"></div>');
searchStatus[key] = false;
}
// Close live-search when clicking outside it
jQuery(document.body).click(function(event) {
var clicked = jQuery(event.target);
if (!(clicked.is('#' + config.id) || clicked.parents('#' + config.id).length || clicked.is('input'))) {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
});
}
});
}
return this.each(function () {
var input = jQuery(this).attr('autocomplete', 'off');
var liveSearchPaddingBorderHoriz = parseInt(liveSearch.css('paddingLeft'), 10) + parseInt(liveSearch.css('paddingRight'), 10) + parseInt(liveSearch.css('borderLeftWidth'), 10) + parseInt(liveSearch.css('borderRightWidth'), 10);
// Re calculates live search's position
var repositionLiveSearch = function () {
var tmpOffset = input.offset();
var tmpWidth = input.outerWidth();
if (config.width != null) {
tmpWidth = config.width;
}
var inputDim = {
left: tmpOffset.left,
top: tmpOffset.top,
width: tmpWidth,
height: input.outerHeight()
};
inputDim.topPos = inputDim.top + inputDim.height;
inputDim.totalWidth = inputDim.width - liveSearchPaddingBorderHoriz;
liveSearch.css({
position: 'absolute',
left: inputDim.left + 'px',
top: inputDim.topPos + 'px',
width: inputDim.totalWidth + 'px'
});
};
var showOrHideLiveSearch = function () {
if (loadingRequestCounter == 0) {
showStatus = false;
for (key in config.url) {
if( searchStatus[key] == true ) {
showStatus = true;
break;
}
}
if (showStatus == true) {
for (key in config.url) {
if( searchStatus[key] == false ) {
liveSearch.find('#' + key).html('');
}
}
showLiveSearch();
} else {
hideLiveSearch();
}
}
};
// Shows live-search for this input
var showLiveSearch = function () {
// Always reposition the live-search every time it is shown
// in case user has resized browser-window or zoomed in or whatever
repositionLiveSearch();
// We need to bind a resize-event every time live search is shown
// so it resizes based on the correct input element
jQuery(window).unbind('resize', repositionLiveSearch);
jQuery(window).bind('resize', repositionLiveSearch);
liveSearch.slideDown(config.duration)
};
// Hides live-search for this input
var hideLiveSearch = function () {
liveSearch.slideUp(config.duration, function () {
config.onSlideUp();
for (key in config.url) {
liveSearch.find('#' + key).html('');
}
});
};
input
// On focus, if the live-search is empty, perform an new search
// If not, just slide it down. Only do this if there's something in the input
.focus(function () {
if (this.value.length > config.minLength ) {
showOrHideLiveSearch();
}
})
// Auto update live-search onkeyup
.keyup(function () {
// Don't update live-search if it's got the same value as last time
if (this.value != this.lastValue) {
input.addClass(config.loadingClass);
var q = this.value;
// Stop previous ajax-request
if (this.timer) {
clearTimeout(this.timer);
}
if( q.length > config.minLength ) {
// Start a new ajax-request in X ms
this.timer = setTimeout(function () {
for (url_key in config.url) {
loadingRequestCounter += 1;
jQuery.ajax({
key: url_key,
url: config.url[url_key] + q,
success: function(data){
if (data.length) {
searchStatus[this.key] = true;
liveSearch.find("#" + this.key).html(data);
} else {
searchStatus[this.key] = false;
}
loadingRequestCounter -= 1;
showOrHideLiveSearch();
}
});
}
}, config.typeDelay);
}
else {
for (url_key in config.url) {
searchStatus[url_key] = false;
}
hideLiveSearch();
}
this.lastValue = this.value;
}
});
});
};
add a background to the loading class
.loading {
background:url('http://path_to_your_picture');
}

Adding click listeners onto code generated in a Javascript object

I am creating a Javascript/jQuery slider class which builds a slideshow on a page when invoked.
Here is my Cycler object code:
//Cycle
var Cycler = function(options) {
this.cycleElement = options.cycleElement;
this.speed = options.speed || 5000;
this.effect = options.effect || "linear";
this.currentItem = null;
this.children = this.addItemsToCycler();
this.buttons = null;
if(options.buttonsEl.length != "") {
this.buttons = this.generateButtons();
}
}
Cycler.prototype.addItemsToCycler = function() {
var children = [];
jQuery(this.cycleElement + " > div.cycle-object").each(function(item, value) {
children.push(value);
});
return children;
}
Cycler.prototype.generateButtons = function() {
var buttons = "<ul>";
var counter = 0;
this.children.forEach(function(item) {
buttons += "<li><a href='#' data-rel='" + counter + "'></a></li>";
counter++;
});
buttons += "</ul>";
jQuery("#cycle-buttons").html(buttons);
}
Cycler.prototype.showItem = function() {
jQuery(this.children).fadeOut("slow");
jQuery(this.children[this.currentItem]).fadeIn("slow");
}
Cycler.prototype.start = function() {
if(this.currentItem == null || this.children.length <= this.currentItem) {
this.currentItem = 0;
}
this.showItem();
var self = this;
interval = window.setInterval(function() {
self.next();
}, this.speed);
}
Cycler.prototype.next = function() {
if(this.currentItem >= (this.children.length - 1)) {
this.currentItem = 0;
} else {
this.currentItem++;
}
this.showItem();
}
Cycler.prototype.prev = function() {
if(this.currentItem <= 0) {
this.currentItem = this.children.length - 1;
} else {
this.currentItem--;
}
this.showItem();
}
Cycler.prototype.pause = function() {
if(this.interval == null) {
console.log("Cycler is already paused");
} else {
window.clearInterval(this.interval);
this.interval = null;
}
}
Cycler.prototype.gotoItem = function(gotoItem) {
this.currentItem = gotoItem;
this.showItem();
}
The markup:
<div id="cycle-wrap">
<div id="background-cycle">
<div data-rel="0" class="cycle-object"></div>
<div data-rel="1" class="cycle-object"></div>
<div data-rel="2" class="cycle-object"></div>
</div>
<div class="inner">
<div id="cycle-buttons">
</div>
</div>
</div>
And my client code which creates an instance of the class:
//Cycler
var cycler = new Cycler({
cycleElement : "#background-cycle",
speed : 5000,
effect : "linear",
buttonsEl : "#cycle-buttons"
});
cycler.start();
Now, if a user supplies an element in the 'buttonsEl' variable which is passed to the class, I want the class to generate a list of li elements which when clicked will take the user to that slide. I have done this via the 'generateButtons' function I have already created the prototype function for this called 'goToItem' as you can see above. I am linking the li elements and the corresponding html using a 'data'rel' attribute.
What I would like to do is add click listeners onto each list element (that is generated in the 'generateButtons' function) which will pass the data-rel attribute through to my 'goToItem' function. Does anyone know of the best way this would be incorporated into my code, keeping it nice and OOP.
Thanks
In your Cycler constructor we could pass the buttonsEl to the generateButtons. Then this method will be able to insert the buttons in the desired element.
// Not sure if you want this comparison. If works by coercion but it's tricky. And it
// will fail if your client doesn't pass a buttonsEl option.
// I would prefer something like this:
// if(options.buttonsEl && options.buttonsEl.length > 0) {
if(options.buttonsEl.length != "") {
this.buttons = this.generateButtons(options.buttonsEl);
}
The generateButtons could be something like this:
Cycler.prototype.generateButtons = function(buttonsEl) {
var $buttons = jQuery("<ul></ul>");
this.children.forEach(function(item, counter) {
$buttons.append("<li><a href='#' data-rel='" + counter + "'></a></li>");
});
// Capture cycler this to be able to invoke the gotoItem method
// within the event handler
var that = this;
$buttons.on('click', 'li', function () {
that.gotoItem($(this).find('a').data('rel'));
});
jQuery(buttonsEl).html($buttons);
return $buttons;
}

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);
})()

JQuery placeholder HTML5 simulator

I have been using the HTML 5 placeholder and just realised that it does not work outside HTML5 devices. As you can see by the code below the placeholder is always in lowercase and the value is always in upper case.
#maphead input::-webkit-input-placeholder {
text-transform:lowercase;
}
#maphead input:-moz-placeholder {
text-transform:lowercase;
}
<input id="start" type="text" spellcheck="false" placeholder="enter your post code" style="text-transform:uppercase;" class="capital"/>
This is all fine except when dealing with non HTML 5 devices. For this I have employed a bastardised bit of javascript.
function activatePlaceholders() {
var detect = navigator.userAgent.toLowerCase();
if (detect.indexOf("safari") > 0) return false;
var inputs = document.getElementsByTagName("input");
for (var i=0;i<inputs.length;i++) {
if (inputs[i].getAttribute("type") == "text") {
var placeholder = inputs[i].getAttribute("placeholder");
if (placeholder.length > 0 || value == placeholder) {
inputs[i].value = placeholder;
inputs[i].onclick = function() {
if (this.value == this.getAttribute("placeholder")) {
this.value = "";
}
return false;
}
inputs[i].onblur = function() {
if (this.value.length < 1) {
this.value = this.getAttribute("placeholder");
$('.capital').each(function() {
var current = $(this).val();
var place = $(this).attr('placeholder');
if (current == place) {
$(this).css('text-transform','lowercase')
}
});
}
}
}
}
}
}
window.onload = function() {
activatePlaceholders();
}
Firstly this Javascript is rancid. There must be an easier JQuery way. Now although this above does work (reasonably) it does not respond to keeping the placeholder in lowercase and the value in uppercase since it sets the value with the placeholder.
I've set you all up with a nice Fiddle http://jsfiddle.net/Z9YLZ/1/
Try something like this:
$(function() {
$('input[type="text"]').each(function () {
$(this).focus(function () {
if ($(this).attr('value') === $(this).attr('placeholder')) {
$(this).css('text-transform','lowercase');
$(this).attr('value', '');
}
}).blur(function () {
if ($(this).attr('value') === '') {
$(this).css('text-transform','uppercase');
$(this).attr('value', $(this).attr('placeholder'));
}
}).blur();
});
});
Edit: Explicitly declare the text-transform to cascade properly.
Try this one, I'm using it for a while and it works perfectly:
(function($, undefined) {
var input = document.createElement('input');
if ('placeholder' in input) {
$.fn.hinttext = $.hinttext = $.noop;
$.hinttext.defaults = {};
delete input;
return;
}
delete input;
var boundTo = {},
expando = +new Date + Math.random() * 100000 << 1,
prefix = 'ht_',
dataName = 'hinttext';
$.fn.hinttext = function(options) {
if (options == 'refresh') {
return $(this).each(function() {
if ($(this).data(dataName) != null) {
focusout.call(this);
}
});
}
options = $.extend({}, $.hinttext.defaults, options);
if (!(options.inputClass in boundTo)) {
$('.' + options.inputClass)
.live('focusin click', function() {
$($(this).data(dataName)).hide();
})
.live('focusout', focusout);
boundTo[options.inputClass] = true;
}
return $(this).each(function(){
var input = $(this),
placeholder = input.attr('placeholder');
if (placeholder && input.data(dataName) === undefined) {
var input_id = input.attr('id'),
label_id = prefix + expando++;
if (!input_id) {
input.attr('id', input_id = prefix + expando++);
}
$('<label/>')
.hide()
.css('position', options.labelPosition)
.addClass(options.labelClass)
.text(placeholder)
.attr('for', input_id)
.attr('id', label_id)
.insertAfter(input);
input
.data(dataName, '#' + label_id)
.addClass(options.inputClass)
.change(function() {
focusout.call(this);
});
}
focusout.call(this);
});
};
$.hinttext = function(selector, options) {
if (typeof selector != 'string') {
options = selector;
selector = 'input[placeholder],textarea[placeholder]';
}
$(selector).hinttext(options);
return $;
};
$.hinttext.defaults = {
labelClass: 'placeholder',
inputClass: 'placeholder',
labelPosition: 'absolute'
};
function focusout() {
var input = $(this),
pos = input.position();
$(input.data(dataName)).css({
left: pos.left + 'px',
top: pos.top + 'px',
width: input.width() + 'px',
height: input.height() + 'px'
})
.text(input.attr('placeholder'))
[['show', 'hide'][!!input.val().length * 1]]();
}
$($.hinttext);
})(jQuery);
You just need to make sure to style label.placeholder with CSS to look the same as HTML5 placeholder text (color: #999)
Try this: http://jsfiddle.net/msm595/Z9YLZ/12/
Bit late but here's what I do. Store all the default values on page load and then clear value text ONLY when it's the default value that is clicked on. This prevents the JS clearing user entered text.
jQuery(document).ready(function($){
var x = 0; // count for array length
$("input.placeholder").each(function(){
x++; //incrementing array length
});
var _values = new Array(x); //create array to hold default values
x = 0; // reset counter to loop through array
$("input.placeholder").each(function(){ // for each input element
x++;
var default_value = $(this).val(); // get default value.
_values[x] = default_value; // create new array item with default value
});
var current_value; // create global current_value variable
$('input.placeholder').focus(function(){
current_value = $(this).val(); // set current value
var is_default = _values.indexOf(current_value); // is current value is also default value
if(is_default > -1){ //i.e false
$(this).val(''); // clear value
}
});
$('input.placeholder').focusout(function(){
if( $(this).val() == ''){ //if it is empty...
$(this).val(current_value); //re populate with global current value
}
});
});

Categories

Resources