Can't use javascript within jpanelmenu - javascript

I'm trying to use this autocomplete search:
<script type="text/javascript">
jQuery(function() {
var availableTags = [
"Comedy",
"Music",
"Radio"
];
jQuery( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
Inside this script:
/**
*
* jPanelMenu 1.4.1 (http://jpanelmenu.com)
* By Anthony Colangelo (http://acolangelo.com)
*
* */
(function($){
$.jPanelMenu = function(options) {
if ( typeof(options) == "undefined" || options == null ) { options = {}; };
var jP = {
options: $.extend({
menu: '#menu',
panel: 'body',
trigger: '.menu-trigger',
excludedPanelContent: 'style, script',
clone: true,
keepEventHandlers: false,
direction: 'left',
openPosition: '250px',
animated: true,
closeOnContentClick: true,
keyboardShortcuts: [
{
code: 27,
open: false,
close: true
},
{
code: 37,
open: false,
close: true
},
{
code: 39,
open: true,
close: true
},
{
code: 77,
open: true,
close: true
}
],
duration: 150,
openDuration: options.duration || 150,
closeDuration: options.duration || 150,
easing: 'ease-in-out',
openEasing: options.easing || 'ease-in-out',
closeEasing: options.easing || 'ease-in-out',
before: function(){ },
beforeOpen: function(){ },
beforeClose: function(){ },
after: function(){ },
afterOpen: function(){ },
afterClose: function(){ },
beforeOn: function(){ },
afterOn: function(){ },
beforeOff: function(){ },
afterOff: function(){ }
},options),
settings: {
transitionsSupported: 'WebkitTransition' in document.body.style ||
'MozTransition' in document.body.style ||
'msTransition' in document.body.style ||
'OTransition' in document.body.style ||
'Transition' in document.body.style
,
transformsSupported: 'WebkitTransform' in document.body.style ||
'MozTransform' in document.body.style ||
'msTransform' in document.body.style ||
'OTransform' in document.body.style ||
'Transform' in document.body.style
,
cssPrefix: '',
panelPosition: 'static',
positionUnits: 'px'
},
menu: '#jPanelMenu-menu',
panel: '.jPanelMenu-panel',
timeouts: {},
clearTimeouts: function() {
clearTimeout(jP.timeouts.open);
clearTimeout(jP.timeouts.afterOpen);
clearTimeout(jP.timeouts.afterClose);
},
setPositionUnits: function() {
var foundUnit = false,
allowedUnits = ['%','px','em']
;
for (var unitID = 0; unitID < allowedUnits.length; unitID++) {
var unit = allowedUnits[unitID];
if ( jP.options.openPosition.toString().substr(-unit.length) == unit )
{
foundUnit = true;
jP.settings.positionUnits = unit;
}
}
if ( !foundUnit ) { jP.options.openPosition = parseInt(jP.options.openPosition) + jP.settings.positionUnits }
},
computePositionStyle: function(open, string) {
var position = (open)?jP.options.openPosition:'0' + jP.settings.positionUnits;
var property = {};
if ( jP.settings.transformsSupported ) {
var direction = (open && jP.options.direction == 'right')?'-':'';
var translate = 'translate3d(' + direction + position + ',0,0)';
var transform = 'transform';
if ( string ) {
property = '';
if ( jP.settings.cssPrefix != '' ) { property = jP.settings.cssPrefix + transform + ':' + translate + ';' }
property += transform + ':' + translate + ';';
} else {
if ( jP.settings.cssPrefix != '' ) { property[jP.settings.cssPrefix + transform] = translate; }
property[transform] = translate;
}
} else {
if ( string ) {
property = '';
property = jP.options.direction + ': ' + position + ';';
} else {
property[jP.options.direction] = position;
}
}
return property;
},
setCSSPrefix: function() {
jP.settings.cssPrefix = jP.getCSSPrefix();
},
setjPanelMenuStyles: function() {
var bg = 'background:#fff',
htmlBG = $('html').css('background-color'),
bodyBG = $('body').css('background-color');
var backgroundGenerator = function(element){
var bgs = [];
$.each(['background-color','background-image','background-position','background-repeat','background-attachment','background-size','background-clip'], function(i,value){
if( element.css(value) !== '' ) {
bgs.push(value+':'+element.css(value));
}
});
return bgs.join(';');
};
if ( bodyBG !== 'transparent' && bodyBG !== "rgba(0, 0, 0, 0)") {
bg = backgroundGenerator($('body'));
} else if ( htmlBG !== 'transparent' && htmlBG !== "rgba(0, 0, 0, 0)") {
bg = backgroundGenerator($('html'));
}
if ( $('#jPanelMenu-style-master').length == 0 ) {
$('body').append('<style id="jPanelMenu-style-master">body{width:100%}.jPanelMenu,body{overflow-x:hidden}#jPanelMenu-menu{display:block;position:fixed;top:0;'+jP.options.direction+':0;height:100%;z-index:-1;overflow-x:hidden;overflow-y:scroll;-webkit-overflow-scrolling:touch}.jPanelMenu-panel{position:static;'+jP.options.direction+':0;top:0;z-index:2;width:100%;min-height:100%;' + bg + ';}</style>');
}
},
setMenuState: function(open) {
var position = (open)?'open':'closed';
$(jP.options.panel).attr('data-menu-position', position);
},
getMenuState: function() {
return $(jP.options.panel).attr('data-menu-position');
},
menuIsOpen: function() {
if ( jP.getMenuState() == 'open' ) return true;
else return false;
},
setMenuStyle: function(styles) {
$(jP.menu).css(styles);
},
setPanelStyle: function(styles) {
$(jP.panel).css(styles);
},
showMenu: function() {
jP.setMenuStyle({
display: 'block'
});
jP.setMenuStyle({
'z-index': '1'
});
},
hideMenu: function() {
jP.setMenuStyle({
'z-index': '-1'
});
jP.setMenuStyle({
display: 'none'
});
},
enableTransitions: function(duration, easing) {
var formattedDuration = duration/1000;
var formattedEasing = jP.getCSSEasingFunction(easing);
jP.disableTransitions();
$('body').append('<style id="jPanelMenu-style-transitions">.jPanelMenu-panel{' + jP.settings.cssPrefix + 'transition: all ' + formattedDuration + 's ' + formattedEasing + '; transition: all ' + formattedDuration + 's ' + formattedEasing + ';}</style>');
},
disableTransitions: function() {
$('#jPanelMenu-style-transitions').remove();
},
getCSSEasingFunction: function(name) {
switch ( name )
{
case 'linear':
return name;
break;
case 'ease':
return name;
break;
case 'ease-in':
return name;
break;
case 'ease-out':
return name;
break;
case 'ease-in-out':
return name;
break;
default:
return 'ease-in-out';
break;
}
},
getJSEasingFunction: function(name) {
switch ( name )
{
case 'linear':
return name;
break;
default:
return 'swing';
break;
}
},
getVendorPrefix: function() {
// Thanks to Lea Verou for this beautiful function. (http://lea.verou.me/2009/02/find-the-vendor-prefix-of-the-current-browser)
if('result' in arguments.callee) return arguments.callee.result;
var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/;
var someScript = document.getElementsByTagName('script')[0];
for(var prop in someScript.style)
{
if(regex.test(prop))
{
// test is faster than match, so it's better to perform
// that on the lot and match only when necessary
return arguments.callee.result = prop.match(regex)[0];
}
}
// Nothing found so far? Webkit does not enumerate over the CSS properties of the style object.
// However (prop in style) returns the correct value, so we'll have to test for
// the precence of a specific property
if('WebkitOpacity' in someScript.style) return arguments.callee.result = 'Webkit';
if('KhtmlOpacity' in someScript.style) return arguments.callee.result = 'Khtml';
return arguments.callee.result = '';
},
getCSSPrefix: function() {
var prefix = jP.getVendorPrefix();
if ( prefix != '' ) { return '-' + prefix.toLowerCase() + '-'; }
return '';
},
openMenu: function(animated) {
if ( typeof(animated) == "undefined" || animated == null ) { animated = jP.options.animated };
jP.clearTimeouts();
jP.options.before();
jP.options.beforeOpen();
jP.setMenuState(true);
jP.showMenu();
var animationChecks = {
none: (!animated)?true:false,
transitions: (animated && jP.settings.transitionsSupported)?true:false
};
if ( animationChecks.transitions || animationChecks.none ) {
if ( animationChecks.none ) jP.disableTransitions();
if ( animationChecks.transitions ) jP.enableTransitions(jP.options.openDuration, jP.options.openEasing);
var newPanelStyle = jP.computePositionStyle(true);
jP.setPanelStyle(newPanelStyle);
jP.timeouts.afterOpen = setTimeout(function(){
jP.options.after();
jP.options.afterOpen();
jP.initiateContentClickListeners();
}, jP.options.openDuration);
}
else {
var formattedEasing = jP.getJSEasingFunction(jP.options.openEasing);
var animationOptions = {};
animationOptions[jP.options.direction] = jP.options.openPosition;
$(jP.panel).stop().animate(animationOptions, jP.options.openDuration, formattedEasing, function(){
jP.options.after();
jP.options.afterOpen();
jP.initiateContentClickListeners();
});
}
},
closeMenu: function(animated) {
if ( typeof(animated) == "undefined" || animated == null ) { animated = jP.options.animated };
jP.clearTimeouts();
jP.options.before();
jP.options.beforeClose();
jP.setMenuState(false);
var animationChecks = {
none: (!animated)?true:false,
transitions: (animated && jP.settings.transitionsSupported)?true:false
};
if ( animationChecks.transitions || animationChecks.none ) {
if ( animationChecks.none ) jP.disableTransitions();
if ( animationChecks.transitions ) jP.enableTransitions(jP.options.closeDuration, jP.options.closeEasing);
var newPanelStyle = jP.computePositionStyle();
jP.setPanelStyle(newPanelStyle);
jP.timeouts.afterClose = setTimeout(function(){
jP.disableTransitions();
jP.hideMenu();
jP.options.after();
jP.options.afterClose();
jP.destroyContentClickListeners();
}, jP.options.closeDuration);
}
else {
var formattedEasing = jP.getJSEasingFunction(jP.options.closeEasing);
var animationOptions = {};
animationOptions[jP.options.direction] = 0 + jP.settings.positionUnits;
$(jP.panel).stop().animate(animationOptions, jP.options.closeDuration, formattedEasing, function(){
jP.hideMenu();
jP.options.after();
jP.options.afterClose();
jP.destroyContentClickListeners();
});
}
},
triggerMenu: function(animated) {
if ( jP.menuIsOpen() ) jP.closeMenu(animated);
else jP.openMenu(animated);
},
initiateClickListeners: function() {
$(document).on('click touchend',jP.options.trigger,function(e){
jP.triggerMenu(jP.options.animated); e.preventDefault();
});
},
destroyClickListeners: function() {
$(document).off('click touchend',jP.options.trigger,null);
},
initiateContentClickListeners: function() {
if ( !jP.options.closeOnContentClick ) return false;
$(document).on('click touchend',jP.panel,function(e){
if ( jP.menuIsOpen() ) jP.closeMenu(jP.options.animated);
e.preventDefault();
});
},
destroyContentClickListeners: function() {
if ( !jP.options.closeOnContentClick ) return false;
$(document).off('click touchend',jP.panel,null);
},
initiateKeyboardListeners: function() {
var preventKeyListeners = ['input', 'textarea', 'select'];
$(document).on('keydown',function(e){
var target = $(e.target),
prevent = false;
$.each(preventKeyListeners, function(){
if (target.is(this.toString())) {
prevent = true;
}
});
if ( prevent ) return true;
for ( mapping in jP.options.keyboardShortcuts ) {
if ( e.which == jP.options.keyboardShortcuts[mapping].code ) {
var key = jP.options.keyboardShortcuts[mapping];
if ( key.open && key.close ) { jP.triggerMenu(jP.options.animated); }
else if ( (key.open && !key.close) && !jP.menuIsOpen() ) { jP.openMenu(jP.options.animated); }
else if ( (!key.open && key.close) && jP.menuIsOpen() ) { jP.closeMenu(jP.options.animated); }
e.preventDefault();
}
}
});
},
destroyKeyboardListeners: function() {
$(document).off('keydown',null);
},
setupMarkup: function() {
$('html').addClass('jPanelMenu');
$(jP.options.panel + ' > *').not(jP.menu + ', ' + jP.options.excludedPanelContent).wrapAll('<div class="' + jP.panel.replace('.','') + '"/>');
var menu = ( jP.options.clone )?$(jP.options.menu).clone(jP.options.keepEventHandlers):$(jP.options.menu);
menu.attr('id', jP.menu.replace('#','')).insertAfter(jP.options.panel + ' > ' + jP.panel);
},
resetMarkup: function() {
$('html').removeClass('jPanelMenu');
$(jP.options.panel + ' > ' + jP.panel + ' > *').unwrap();
$(jP.menu).remove();
},
init: function() {
jP.options.beforeOn();
jP.setPositionUnits();
jP.setCSSPrefix();
jP.initiateClickListeners();
if ( Object.prototype.toString.call(jP.options.keyboardShortcuts) === '[object Array]' ) { jP.initiateKeyboardListeners(); }
jP.setjPanelMenuStyles();
jP.setMenuState(false);
jP.setupMarkup();
jP.setPanelStyle({ position: (( jP.options.animated && jP.settings.panelPosition === 'static' )?'relative':jP.settings.panelPosition) });
jP.setMenuStyle({ width: jP.options.openPosition });
jP.closeMenu(false);
jP.options.afterOn();
},
destroy: function() {
jP.options.beforeOff();
jP.closeMenu();
jP.destroyClickListeners();
if ( Object.prototype.toString.call(jP.options.keyboardShortcuts) === '[object Array]' ) { jP.destroyKeyboardListeners(); }
jP.resetMarkup();
var childrenStyles = {};
childrenStyles[jP.options.direction] = 'auto';
jP.options.afterOff();
}
};
return {
on: jP.init,
off: jP.destroy,
trigger: jP.triggerMenu,
open: jP.openMenu,
close: jP.closeMenu,
isOpen: jP.menuIsOpen,
menu: jP.menu,
getMenu: function() { return $(jP.menu); },
panel: jP.panel,
getPanel: function() { return $(jP.panel); },
setPosition: function(position) {
if ( typeof(position) == "undefined" || position == null ) {
position = jP.options.openPosition
}
jP.options.openPosition = position;
jP.setMenuStyle({ width: jP.options.openPosition });
}
};
};
})(jQuery);
</script>
<script type="text/javascript">
jQuery(function() {
var jPM = jQuery.jPanelMenu();
var jPM = jQuery.jPanelMenu({
menu: '#menu-selector',
trigger: '.menu-trigger-selector',
duration: 300
});
jPM.on();
})
</script>
The HTML looks like
<div class="menu-trigger-selector"><img src="https://lh3.googleusercontent.com/-G1THV0EXgLY/VQgWdKfzIvI/AAAAAAAAAJg/_AtOhuTN9JI/s28-no/hamburger-menu-icon.png" alt="Menu Button" title="Menu Button"></div>
<div id="menu-selector" style="display:none;">
<ul class="info">
<li id="about" class="noselect">Home</li>
<li id="faq" class="noselect">About</li>
<li id="contribute" class="noselect">Contact</li>
</ul>
<ul class="login-register">
<li id="login" class="noselect">Login</li>
<li id="register" class="noselect">Register</li>
</ul>
<div class="ui-widget">
<input id="tags" placeholder="Search"></input>
</div>
<ul class="podcast-list">
<li>Main1
<ul class="podcasts">
<li>Sub</li>
<li>Sub</li>
<li>Sub</li>
<li>Sub</li>
</ul>
</li>
</ul>
</div>
<div class="container">
...
</div>
Loading resources in this order
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../jquery.once.js?v=1.2"></script>
<script src="../drupal.js?nmk3bg"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
No jquery works at all though. Scripts work fine anywhere in the body, but not inside the side menu. There are no console errors. I've tried 2 other side menus but javascript doesn't work within them either. I need help either fixing this one or finding another one that supports javascript.

I see you use $ to call jQuery. Try this, it may turn out to be helpful.
jQuery( document ).ready(function( $ ){
// Do stuff here
// For example, initialize jPanel in here
});
Let me know how this turns out.

Related

jQuery stylesheet wont load

Alright! So I got a jQuery sheet in "borrowing" from another page. The jQuery works fine with the code that links it to the original location.
<script type="text/javascript" src="http://restaurantleduc.com/wp-content/themes/leduc/js/LD.js"></script>
However, when I try to export the whole code from the original website it wont work for me. Not in my script and not in an stylesheet for itself... Could really use some help on this one . :) Here is the original "raw" code:
if ( !window.$ ) window.$ = window.jQuery;
// Create Namespace
var LD = window.LD || {};
/* EVENT MANAGER */
LD.EM = LD.EM || $({});
/*
* EVENTS
*/
LD.Events = {
APP_READY : "APP_READY",
SCROLLED : "SCROLLED",
RESIZED : "RESIZED"
};
// VARS-CONST
LD.WIDTH = 0;
LD.HEIGHT = 0;
$(window).ready(function(){
$("html").addClass( (LD.Utils.hasTouch() ? "touch" : "no-touch") );
LD.Resize.init();
LD.Scroll.init();
LD.Menu.init();
LD.Carousel.init();
LD.Footer.init();
if ( $(".home").length )
LD.Home.init();
if ( $(".news").length )
LD.News.init();
});
$(window).load(function() {
$(window).trigger("resize");
$(window).trigger("scroll");
});
LD.Utils = {
hasTouch : function() {
return 'ontouchstart' in window;
},
isValidEmailAddress : function (emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
},
map : function(value, start1, stop1, start2, stop2) {
return start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
},
createCookie : function(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
document.cookie = name+"="+value+expires+"; path=/";
},
readCookie : function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
eraseCookie : function(name) {
LD.Utils.createCookie(name,"",-1);
}
};
LD.Carousel = LD.Carousel ||Â {
sliders : [],
init : function() {
if ( $(".article-carousel").length === 0 ) return;
this.initSwipe();
},
initSwipe : function() {
var self = this;
$(".article-carousel .swipe").each( function( i, swipe ) {
var slider = new Swipe(swipe, {
speed: 900,
continuous: true,
callback : $.proxy( self.callbackSlider, self )
});
$(swipe).parents(".article-preview").data("index", i);
self.sliders.push( slider );
});
imagesLoaded( $('body'), function() {
LD.EM.trigger( LD.Events.RESIZED );
});
$(".btn-next, .btn-prev", ".article-carousel").on("click", $.proxy( this.navSwipe, this ));
$(".btn-dot", ".article-carousel").on("click", $.proxy( this.dotSwipe, this ));
},
callbackSlider : function(index, el) {
var
$el = $(el),
$parent = $el.parents(".article-preview, .article-full"),
sliderIndex = $parent.data("index") || 0,
slider = this.sliders[ sliderIndex ];
$(".btn-dot.selected", $parent).removeClass("selected");
$(".btn-dot:eq(" + slider.getPos() + ")", $parent).addClass("selected");
},
navSwipe : function(e) {
e.preventDefault();
var
$el = $(e.currentTarget),
sliderIndex = $el.parents(".article-preview").data("index") ||Â 0,
slider = this.sliders[ sliderIndex ];
if ( $el.hasClass("btn-prev") ) {
slider.prev();
} else {
slider.next();
}
},
dotSwipe : function(e) {
e.preventDefault();
var
$el = $(e.currentTarget),
sliderIndex = $el.parents(".article-preview").data("index") ||Â 0,
slider = this.sliders[ sliderIndex ];
slider.slide( $el.data("index") );
}
};
LD.Footer = LD.Footer ||Â {
init : function() {
this.initBtn();
this.initNewsletter();
},
initBtn : function() {
$("footer .btn-top").on("click", $.proxy( this.onTopClick, this ));
},
onTopClick : function(e) {
e.preventDefault();
$("html, body").animate({
scrollTop : 0
}, 1200);
},
initNewsletter : function () {
var
$context = $("footer"),
email;
$(".form-newsletter", $context).on("submit", function(e){
e.preventDefault();
$(".valid-error, .post-error, .valid", $context).hide();
email = $(".form-email", this).val();
if ( LD.Utils.isValidEmailAddress(email) ) {
$.post( $(this).attr("action"), $(this).serialize(), function() {
$(".valid", $context).show();
})
.fail(function() {
$(".post-error", $context).show();
});
} else {
$(".valid-error", $context).show();
}
});
},
};
LD.Menu = LD.Menu ||Â {
init : function() {
this.initLang();
},
initLang : function() {
var newlang;
$(".btn-lang").on("click", function(e){
e.preventDefault();
newlang = $(this).data("lang");
LD.Utils.eraseCookie("leduc_lang");
LD.Utils.createCookie("leduc_lang", newlang, 365);
window.location.reload();
});
}
};
LD.Resize = LD.Resize ||Â {
init : function() {
LD.WIDTH = $(window).width();
LD.HEIGHT = $(window).height();
$(window).on("resize", $.proxy(this.onResize, this));
},
kill : function() {
$(window).off("resize", $.proxy(this.onResize, this));
},
onResize : function() {
LD.WIDTH = $(window).width();
LD.HEIGHT = $(window).height();
LD.EM.trigger( LD.Events.RESIZED );
}
};
LD.Scroll = LD.Scroll ||Â {
$body : null,
$carte : null,
$lunch : null,
$starters : null,
$mains : null,
$restaurant : null,
scrollPos : null,
scrollLunch : null,
scrollStarters : null,
scrollMains : null,
scrollRestaurant : null,
init : function() {
this.$body = $("body");
this.$carte = $(".home-carte");
this.$lunch = $(".block-lunch");
this.$starters = $(".block-starters");
this.$mains = $(".block-mains");
this.$restaurant = $(".home-restaurant");
this.onResized();
LD.EM.on( LD.Events.RESIZED, $.proxy( this.onResized, this ) );
$(window).on("scroll", $.proxy(this.onScroll, this));
},
kill : function() {
$(window).off("scroll", $.proxy(this.onScroll, this));
},
onResized : function() {
if ( this.$carte.length === 0 ) return;
var
offset = Math.round(LD.HEIGHT*0.5),
offsetTopCarte = this.$carte.position().top;
this.scrollLunch = offsetTopCarte - offset;
this.scrollStarters = offsetTopCarte + this.$starters.position().top - offset - 150;
this.scrollMains = offsetTopCarte + this.$mains.position().top - offset - 150;
this.scrollRestaurant = this.$restaurant.position().top - offset;
},
onScroll : function() {
this.checkScroll( 128, this.$body, "sticky" );
if ( !LD.Utils.hasTouch() ) {
this.checkScroll( this.scrollLunch, this.$lunch, "show-lunch" );
this.checkScroll( this.scrollStarters, this.$starters, "show-starters" );
this.checkScroll( this.scrollMains, this.$mains, "show-mains" );
this.checkScroll( this.scrollRestaurant, this.$restaurant, "show-restaurant" );
}
LD.EM.trigger( LD.Events.SCROLLED );
},
checkScroll : function( limit, $el, className ) {
var currentScrollPos = $(document).scrollTop();
LD.scrollPos = currentScrollPos;
if ( currentScrollPos > limit ) {
$el.addClass(className);
} else {
$el.removeClass(className);
}
}
};
LD.Home = LD.Home ||Â {
$sliders : null,
sliders : [],
init : function() {
this.$sliders = $(".swipe-container");
this.initMenu();
this.initSliders();
this.initCarte();
// GOOGLE MAPS
this.initMap();
LD.EM.on( LD.Events.SCROLLED, $.proxy( this.onScrolled, this ) );
LD.EM.on( LD.Events.RESIZED, $.proxy( this.onResized, this ) );
},
initMenu : function () {
$(".logo a").on("click", function(e) {
if ( $(".home").length ) {
e.preventDefault();
$('html,body').animate({
scrollTop: 0
}, 1000);
}
});
$("a.btn-internal").on("click", function(e) {
e.preventDefault();
var target = $(this).attr("href").replace("/", "");
$('html,body').animate({
scrollTop: $( target ).offset().top - 110
}, 1000);
});
},
initSliders : function() {
var self = this;
$(".swipe").each( function( i, swipe ) {
var slider = new Swipe(swipe, {
auto : 6000,
speed: 900,
continuous: true,
callback : $.proxy( self.callbackSlider, self )
});
self.sliders.push( slider );
});
$(".btn-next, .btn-prev").on("click", $.proxy( this.navSwipe, this ));
$(".btn-dot").on("click", $.proxy( this.dotSwipe, this ));
},
navSwipe : function(e) {
e.preventDefault();
var
$el = $(e.currentTarget),
sliderIndex = $el.parents(".swipe-container").data("index"),
slider = this.sliders[ sliderIndex ];
if ( $el.hasClass("btn-prev") ) {
slider.prev();
} else {
slider.next();
}
},
dotSwipe : function(e) {
e.preventDefault();
var
$el = $(e.currentTarget),
sliderIndex = $el.parents(".swipe-container").data("index"),
slider = this.sliders[ sliderIndex ];
slider.slide( $el.data("index") );
},
callbackSlider : function( index, el ) {
var
$el = $(el),
$parent = $el.parents(".swipe-container"),
sliderIndex = $parent.data("index"),
slider = this.sliders[ sliderIndex ];
$(".btn-dot.selected", $parent).removeClass("selected");
$(".btn-dot:eq(" + slider.getPos() + ")", $parent).addClass("selected");
},
initMap : function() {
var
$el = $(".map"),
center = new google.maps.LatLng( $el.data("lat"), $el.data("lng") ),
mapOptions = {
scrollwheel : false,
disableDefaultUI : true,
center: center,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles : [{"featureType":"all","stylers":[{"saturation":0},{"hue":"#e7ecf0"}]},{"featureType":"road","stylers":[{"saturation":-70}]},{"featureType":"transit","stylers":[{"visibility":"off"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"water","stylers":[{"visibility":"simplified"},{"saturation":-60}]}]
},
map = new google.maps.Map($el[0], mapOptions);
new google.maps.Marker({
"position": center,
"map": map
});
},
initCarte : function() {
this.$carteWrap = $(".home-carte");
this.$carteHeight = this.$carteWrap.height();
this.$carteTop = this.$carteWrap.position().top;
this.$fishes = $(".fish", this.$carteWrap);
},
onScrolled : function() {
if ( LD.Utils.hasTouch() ) return;
if ( this.$carteTop < LD.scrollPos + LD.HEIGHT && this.$carteTop + this.$carteHeight > LD.scrollPos ) {
var
val = this.$carteTop - (LD.scrollPos + LD.HEIGHT),
max = this.$carteHeight + LD.HEIGHT,
p = LD.Utils.map( val, 0, max, 0, 150 ),
$fish = null;
this.$fishes.each(function (i, fish) {
$fish = $(fish);
$fish.css("transform", "translateY(" + (p * $fish.data("speed")) + "%)");
});
}
},
onResized : function() {
}
};
LD.News = LD.News ||Â {
init : function() {
this.initBtnTop();
},
initBtnTop : function() {
$(".btn-top").on("click", $.proxy(this.toTop, this));
},
toTop : function() {
$("html, body").animate({
"scrollTop" : 0
}, 300);
}
};
Are you linking the jquery library? If you don't want to download and host it yourself you can use the link below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Wordpress click and search with autocomplete

I have a problem with implementing my working script into my website. The local self-made script works perfectly. It uses jQuery autocomplete. When I type in 3 letters it will display the results. When I click on the results it will auto search.
I am trying to implement this into my current search box but I can't get it to work. In my local file I get the answers from an array but in my Wordpress version am using Ajax request to get the answers.
I am not sure which arguments to use in my WordPress function. Who can help me?
My working file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="jquery-ui.css">
<script src="main.js"></script>
<title>Autocomplete</title>
</head>
<body>
<label for="states">Geef een naam op:</label>
<input id="states">
<button id="go" style="display: none;" >GO</button>
<div id="no-result" style="display: none;">State not found.</div>
<p id="resultaten"></p>
<script>
function weergeven() {
var x = document.getElementById("Medewerkers").value;
document.getElementById("resultaten").innerHTML = x;
}
</script>
</body>
</html>
Javascript
$("#states").keypress(function (event) {
if (event.which == 13) {
event.preventDefault();
btnGoClick();
}
});
$(function () {
var stateList = [{
"value": "Jurre"
}, {
"value": "hans"
}, {
"value": "Roy"
}, {
"value": "lars"
}, {
"value": "Ewald"
}, {
"value": "Remy"
}, {
"value": "Marvin"
}, {
"value": "Niek"
}, {
"value": "Arnold"
}];
$("#states").autocomplete({
source: stateList,
autoFocus: true,
minLength: 3,
select: function (event, ui) {
btnGoClick(ui.item.value);
}
});
});
function btnGoClick(value) {
document.getElementById("resultaten").innerHTML = value;
}
Where it need to work:
<script>
jQuery( document ).ready(function(){
jQuery('.autocompl').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'private link',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
},
select: function (event, ui) {
console.log("Hij doet het");
}
});
});
function btnGoClick() {
console.log("Hij doet het")
}
</script>
Nothing is showing up on my console, no error or console.log
Who can Help me?
Edit: Here is the response code:
var wpAjax = jQuery.extend( {
unserialize: function( s ) {
var r = {}, q, pp, i, p;
if ( !s ) { return r; }
q = s.split('?'); if ( q[1] ) { s = q[1]; }
pp = s.split('&');
for ( i in pp ) {
if ( jQuery.isFunction(pp.hasOwnProperty) && !pp.hasOwnProperty(i) ) { continue; }
p = pp[i].split('=');
r[p[0]] = p[1];
}
return r;
},
parseAjaxResponse: function( x, r, e ) { // 1 = good, 0 = strange (bad data?), -1 = you lack permission
var parsed = {}, re = jQuery('#' + r).empty(), err = '';
if ( x && typeof x == 'object' && x.getElementsByTagName('wp_ajax') ) {
parsed.responses = [];
parsed.errors = false;
jQuery('response', x).each( function() {
var th = jQuery(this), child = jQuery(this.firstChild), response;
response = { action: th.attr('action'), what: child.get(0).nodeName, id: child.attr('id'), oldId: child.attr('old_id'), position: child.attr('position') };
response.data = jQuery( 'response_data', child ).text();
response.supplemental = {};
if ( !jQuery( 'supplemental', child ).children().each( function() {
response.supplemental[this.nodeName] = jQuery(this).text();
} ).length ) { response.supplemental = false; }
response.errors = [];
if ( !jQuery('wp_error', child).each( function() {
var code = jQuery(this).attr('code'), anError, errorData, formField;
anError = { code: code, message: this.firstChild.nodeValue, data: false };
errorData = jQuery('wp_error_data[code="' + code + '"]', x);
if ( errorData ) { anError.data = errorData.get(); }
formField = jQuery( 'form-field', errorData ).text();
if ( formField ) { code = formField; }
if ( e ) { wpAjax.invalidateForm( jQuery('#' + e + ' :input[name="' + code + '"]' ).parents('.form-field:first') ); }
err += '<p>' + anError.message + '</p>';
response.errors.push( anError );
parsed.errors = true;
} ).length ) { response.errors = false; }
parsed.responses.push( response );
} );
if ( err.length ) { re.html( '<div class="error">' + err + '</div>' ); }
return parsed;
}
if ( isNaN(x) ) { return !re.html('<div class="error"><p>' + x + '</p></div>'); }
x = parseInt(x,10);
if ( -1 == x ) { return !re.html('<div class="error"><p>' + wpAjax.noPerm + '</p></div>'); }
else if ( 0 === x ) { return !re.html('<div class="error"><p>' + wpAjax.broken + '</p></div>'); }
return true;
},
invalidateForm: function ( selector ) {
return jQuery( selector ).addClass( 'form-invalid' ).find('input').one( 'change wp-check-valid-field', function() { jQuery(this).closest('.form-invalid').removeClass( 'form-invalid' ); } );
},
validateForm: function( selector ) {
selector = jQuery( selector );
return !wpAjax.invalidateForm( selector.find('.form-required').filter( function() { return jQuery('input:visible', this).val() === ''; } ) ).length;
}
}, wpAjax || { noPerm: 'Sorry, you are not allowed to do that.', broken: 'An unidentified error has occurred.' } );
// Basic form validation
jQuery(document).ready( function($){
$('form.validate').submit( function() { return wpAjax.validateForm( $(this) ); } );
});

Need help changing default js toggle state on page load

I'm using a Youtube-TV JS plugin for a client site (https://github.com/Giorgio003/Youtube-TV ). The player loads with a playlist in an open state, and I need to have it load with the toggle closed, showing the array of playlists, can anyone help?
my codepen for the player is here
http://codepen.io/raldesign/pen/OVYXvK
(function(win, doc) {
'use strict';
var apiKey = 'AIzaSyAFMzeux_Eu933wk5U8skMzUzA-urgVgsY';
var YTV = YTV || function(id, opts){
var noop = function(){},
settings = {
apiKey: apiKey,
element: null,
user: null,
channelId: null,
fullscreen: false,
accent: '#fff',
controls: true,
annotations: false,
autoplay: false,
chainVideos: true,
browsePlaylists: false,
playerTheme: 'dark',
listTheme: 'dark',
responsive: false,
playId:'',
sortList: false,
reverseList: false,
shuffleList: false,
wmode: 'opaque',
events: {
videoReady: noop,
stateChange: noop
}
},
cache = {
data: {},
remove: function (url) {
delete cache.data[url];
},
exist: function (url) {
return cache.data.hasOwnProperty(url) && cache.data[url] !== null;
},
get: function (url) {
return cache.data[url];
},
set: function (url, data) {
cache.remove(url);
cache.data[url] = data;
}
},
utils = {
events: {
addEvent: function addEvent(element, eventName, func) {
if (element.addEventListener) {
return element.addEventListener(eventName, func, false);
} else if (element.attachEvent) {
return element.attachEvent("on" + eventName, func);
}
},
removeEvent: function addEvent(element, eventName, func) {
if (element.addEventListener) {
return element.removeEventListener(eventName, func, false);
} else if (element.attachEvent) {
return element.detachEvent("on" + eventName, func);
}
},
prevent: function(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
},
addCSS: function(css){
var head = doc.getElementsByTagName('head')[0],
style = doc.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(doc.createTextNode(css));
}
head.appendChild(style);
},
addCommas: function(str){
var x = str.split('.'),
x1 = x[0],
x2 = x.length > 1 ? '.' + x[1] : '',
rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
parentUntil: function(el, attr) {
while (el.parentNode) {
if (el.getAttribute && el.getAttribute(attr)){
return el;
}
el = el.parentNode;
}
return null;
},
ajax: {
get: function(url, fn){
if (cache.exist(url)) {
fn.call(this, JSON.parse(cache.get(url)));
} else {
var handle;
if (win.XDomainRequest && !(navigator.appVersion.indexOf("MSIE 8")==-1 || navigator.appVersion.indexOf("MSIE 9")==-1)) { // CORS for IE8,9
handle = new XDomainRequest();
handle.onload = function(){
cache.set(url, handle.responseText);
fn.call(this, JSON.parse(handle.responseText));
if (Object.prototype.hasOwnProperty.call(JSON.parse(handle.responseText), 'error')){
cache.remove(url);
var e = JSON.parse(handle.responseText);
console.log('Youtube-TV Error: Youtube API Response: '+e.error.errors[0].reason+'\n'+ 'Details: '+e.error.errors[0].message);
}
};
} else if (win.XMLHttpRequest){ // Modern Browsers
handle = new XMLHttpRequest();
}
handle.onreadystatechange = function(){
if (handle.readyState === 4 && handle.status === 200){
cache.set(url, handle.responseText);
fn.call(this, JSON.parse(handle.responseText));
} else if (handle.readyState === 4){
var e = JSON.parse(handle.responseText);
console.log('Youtube-TV Error: Youtube API Response: '+e.error.errors[0].reason+'\n'+ 'Details: '+e.error.errors[0].message);
}
};
handle.open("GET",url,true);
handle.send();
}
}
},
endpoints: {
base: 'https://www.googleapis.com/youtube/v3/',
userInfo: function(){
return utils.endpoints.base+'channels?'+settings.cid+'&key='+apiKey+'&part=snippet,contentDetails,statistics';
},
playlistInfo: function(pid){
return utils.endpoints.base+'playlists?id='+pid+'&key='+apiKey+'&maxResults=50&part=snippet';
},
userPlaylists: function(){
return utils.endpoints.base+'playlists?channelId='+settings.channelId+'&key='+apiKey+'&maxResults=50&part=snippet';
},
playlistVids: function(){
return utils.endpoints.base+'playlistItems?playlistId='+settings.pid+'&key='+apiKey+'&maxResults=50&part=contentDetails';
},
videoInfo: function(){
return utils.endpoints.base+'videos?id='+settings.videoString+'&key='+apiKey+'&maxResults=50&part=snippet,contentDetails,status,statistics';
}
},
deepExtend: function(destination, source) {
var property;
for (property in source) {
if (source[property] && source[property].constructor && source[property].constructor === Object) {
destination[property] = destination[property] || {};
utils.deepExtend(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
}
},
prepare = {
youtube: function(){
if(typeof YT=='undefined'){
var tag = doc.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = doc.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
},
build: function(){
if (settings.channelId){
settings.cid = 'id='+settings.channelId;
} else if(settings.user){
settings.cid = 'forUsername='+settings.user;
}
settings.element.className = "ytv-canvas";
if(settings.fullscreen){
settings.element.className += " ytv-full";
}
utils.addCSS( '#'+id+' .ytv-list .ytv-active a{border-left-color: '+(settings.accent)+';}' );
// Responsive CSS
if(settings.responsive){
utils.addCSS('#'+id+' .ytv-video{'
+'position: relative; padding-bottom: 39.4%; /* 16:9 of 70%*/'
+'height: 0; width: 70%;'
+'} #'+id+' .ytv-video iframe{'
+'position: absolute; top: 0; left: 0;'
+'} #'+id+' .ytv-list{'
+'width: 30%;'
+'} #'+id+' .ytv-playlist-open .ytv-arrow{'
+'top: 0px;}'
+'#media only screen and (max-width:992px) {'
+'#'+id+' .ytv-list{'
+'position: relative; display: block;'
+'width: 0; padding-bottom: 40%;'
+'left: auto; right: auto;'
+'top: auto; width: 100%;'
+'} #'+id+' .ytv-video{'
+'position: relative; padding-bottom: 56.25%; /* 16:9 */'
+'height: 0; position: relative;'
+'display: block; left: auto;'
+'right: auto; top: auto; width: 100%;'
+'}}'
);
}
// Temp Scroll Bar fix
if (settings.listTheme == 'dark'){
utils.addCSS( ' #'+id+'.ytv-canvas ::-webkit-scrollbar{border-left: 1px solid #000;}'
+ ' #'+id+'.ytv-canvas ::-webkit-scrollbar-thumb{background: rgba(255,255,255,0.2);}');
}
// Optional Light List Theme
if(settings.listTheme == 'light'){
utils.addCSS( ' #'+id+'.ytv-canvas{background: #ccc;}'
+ ' #'+id+'.ytv-canvas ::-webkit-scrollbar{border-left: 1px solid rgba(28,28,28,0.1);}'
+ ' #'+id+'.ytv-canvas ::-webkit-scrollbar-thumb{background: rgba(28,28,28,0.3);}'
+ ' #'+id+' .ytv-list .ytv-active a{background: rgba(0,0,0,0.2);}'
+ ' #'+id+' .ytv-list a{color: #282828; border-top: 1px solid rgba(0,0,0,0.1); border-bottom: 1px solid rgba(204,204,204,0.5);}'
+ ' #'+id+' .ytv-list a:hover, #'+id+' .ytv-list-header .ytv-playlists a:hover{ background: rgba(0,0,0,0.2);}'
+ ' #'+id+' .ytv-list a:active, #'+id+' .ytv-list-header .ytv-playlists a:active{ background: rgba(0,0,0,0.2);}'
+ ' #'+id+' .ytv-list .ytv-thumb-stroke{outline: 1px solid rgba(0,0,0,0.1);}'
+ ' #'+id+' .ytv-list .ytv-thumb{outline: 1px solid rgba(255,255,255,0.5);}'
+ ' #'+id+' .ytv-list-header{-webkit-box-shadow: 0 1px 2px rgba(255, 255, 255, 0.2); -moz-box-shadow: 0 1px 2px rgba(255, 255, 255, 0.2); box-shadow: 0 1px 2px rgba(255, 255, 255, 0.2);}'
+ ' #'+id+' .ytv-list-header a{background: rgba(0,0,0,0.2);}'
+ ' #'+id+' .ytv-playlists{background: #ccc;}'
);
}
},
userUploads: function(userInfo){
if (userInfo && userInfo.items.length > 0){
settings.pid = userInfo.items[0].contentDetails.relatedPlaylists.uploads;
utils.ajax.get( utils.endpoints.playlistVids(), prepare.compileVideos );
} else console.log ('Youtube-TV Error: API returned no matches for: '+(settings.channelId ? settings.channelId : settings.user)+'\nPlease ensure it was entered correctly and in the appropriate field shown below. \nuser: \'username\' or channelId: \'UCxxxx...\'');
},
selectedPlaylist: function(playlistInfo){
if (playlistInfo && playlistInfo.items.length > 0) {
if (!settings.channelId && !settings.user){
settings.cid = ('id='+(settings.channelId = playlistInfo.items[0].snippet.channelId));
}
settings.currentPlaylist = playlistInfo.items[0].snippet.title;
settings.pid = playlistInfo.items[0].id;
utils.ajax.get( utils.endpoints.playlistVids(), prepare.compileVideos );
} else console.log ('Youtube-TV Error: API returned no matches for playlist(s): '+settings.playlist);
},
compileVideos: function(res){
if (res && res.items.length > 0){
var playlists = res.items,
i;
settings.videoString = '';
for(i=0; i<playlists.length; i++){
settings.videoString += playlists[i].contentDetails.videoId;
if (i<playlists.length-1){ settings.videoString += ',';}
}
utils.ajax.get( utils.endpoints.videoInfo(), prepare.compileList );
} else console.log ('Youtube-TV Error: Empty playlist');
},
playlists: function(res){
if(res && res.items.length > 0){
var list = '<div class="ytv-playlists"><ul>',
playlists = res.items,
i;
for(i=0; i<playlists.length; i++){
var data = {
title: playlists[i].snippet.title,
plid: playlists[i].id,
thumb: playlists[i].snippet.thumbnails.medium.url
};
list += '<a href="#" data-ytv-playlist="'+(data.plid)+'">';
list += '<div class="ytv-thumb"><div class="ytv-thumb-stroke"></div><img src="'+(data.thumb)+'"></div>';
list += '<span>'+(data.title)+'</span>';
list += '</a>';
}
list += '</ul></div>';
var lh = settings.element.getElementsByClassName('ytv-list-header')[0],
headerLink = lh.children[0];
headerLink.href="#";
headerLink.target="";
headerLink.setAttribute('data-ytv-playlist-toggle', 'true');
settings.element.getElementsByClassName('ytv-list-header')[0].innerHTML += list;
lh.className += ' ytv-has-playlists';
} else console.log ('Youtube-TV Error: Returned no playlists');
},
compileList: function(data){
if(data && data.items.length > 0){
utils.ajax.get( utils.endpoints.userInfo(), function(userInfo){
var list = '',
user = {
title: userInfo.items[0].snippet.title,
url: '//youtube.com/channel/'+userInfo.items[0].id,
thumb: userInfo.items[0].snippet.thumbnails['default'].url,
summary: userInfo.items[0].snippet.description,
subscribers: userInfo.items[0].statistics.subscriberCount,
views: userInfo.items[0].statistics.viewCount
},
videos = data.items,
first = true,
i;
settings.channelId = userInfo.items[0].id;
if(settings.currentPlaylist) user.title += ' · '+(settings.currentPlaylist);
if (settings.sortList) videos.sort(function(a,b){if(a.snippet.publishedAt > b.snippet.publishedAt) return -1;if(a.snippet.publishedAt < b.snippet.publishedAt) return 1;return 0;});
if (settings.reverseList) videos.reverse();
if (settings.shuffleList) {
videos = function (){for(var j, x, i = videos.length; i; j = Math.floor(Math.random() * i), x = videos[--i], videos[i] = videos[j], videos[j] = x);return videos;}();
}
list += '<div class="ytv-list-header">';
list += '<a href="'+(user.url)+'" target="_blank">';
list += '<img src="'+(user.thumb)+'">';
list += '<span><i class="ytv-arrow down"></i>'+(user.title)+'</span>';
list += '</a>';
list += '</div>';
list += '<div class="ytv-list-inner"><ul>';
for(i=0; i<videos.length; i++){
if(videos[i].status.embeddable){
var video = {
title: videos[i].snippet.title,
slug: videos[i].id,
link: 'https://www.youtube.com/watch?v='+videos[i].id,
published: videos[i].snippet.publishedAt,
stats: videos[i].statistics,
duration: (videos[i].contentDetails.duration),
thumb: videos[i].snippet.thumbnails.medium.url
};
var durationString = video.duration.match(/[0-9]+[HMS]/g);
var h = 0, m = 0, s = 0, time = '';
durationString.forEach(function (duration) {
var unit = duration.charAt(duration.length-1);
var amount = parseInt(duration.slice(0,-1));
switch (unit) {
case 'H': h = (amount > 9 ? '' + amount : '0' + amount); break;
case 'M': m = (amount > 9 ? '' + amount : '0' + amount); break;
case 'S': s = (amount > 9 ? '' + amount : '0' + amount); break;
}
});
if (h){ time += h+':';}
if (m){ time += m+':';} else { time += '00:';}
if (s){ time += s;} else { time += '00';}
var isFirst = '';
if(settings.playId==video.slug){
isFirst = ' class="ytv-active"';
first = video.slug;
} else if(first===true){
first = video.slug;
}
list += '<li'+isFirst+'><a href="#" data-ytv="'+(video.slug)+'" class="ytv-clear">';
list += '<div class="ytv-thumb"><div class="ytv-thumb-stroke"></div><span>'+(time)+'</span><img src="'+(video.thumb)+'"></div>';
list += '<div class="ytv-content"><b>'+(video.title)+'</b>';
if (video.stats)
{
list+='</b><span class="ytv-views">'+utils.addCommas(video.stats.viewCount)+' Views</span>';
}
list += '</div></a></li>';
}
}
list += '</ul></div>';
settings.element.innerHTML = '<div class="ytv-relative"><div class="ytv-video"><div id="ytv-video-player"></div></div><div class="ytv-list">'+list+'</div></div>';
if(settings.element.getElementsByClassName('ytv-active').length===0){
settings.element.getElementsByTagName('li')[0].className = "ytv-active";
}
var active = settings.element.getElementsByClassName('ytv-active')[0];
active.parentNode.parentNode.scrollTop = active.offsetTop;
action.logic.loadVideo(first, settings.autoplay);
if (settings.playlist){
utils.ajax.get( utils.endpoints.playlistInfo(settings.playlist), prepare.playlists );
} else if(settings.browsePlaylists){
utils.ajax.get( utils.endpoints.userPlaylists(), prepare.playlists );
}
});
} else console.log ('Youtube-TV Error: Empty video list');
}
},
action = {
logic: {
playerStateChange: function(d){
console.log(d);
},
loadVideo: function(slug, autoplay){
var house = settings.element.getElementsByClassName('ytv-video')[0];
var counter = settings.element.getElementsByClassName('ytv-video-playerContainer').length;
house.innerHTML = '<div id="ytv-video-player'+id+counter+'" class="ytv-video-playerContainer"></div>';
cache.player = new YT.Player('ytv-video-player'+id+counter, {
videoId: slug,
events: {
onReady: settings.events.videoReady,
onStateChange: function(e){
if( (e.target.getPlayerState()===0) && settings.chainVideos ){
var ns = settings.element.getElementsByClassName('ytv-active')[0].nextSibling,
link = ns.children[0];
link.click();
}
settings.events.stateChange.call(this, e);
}
},
playerVars: {
enablejsapi: 1,
origin: doc.domain,
controls: settings.controls ? 1 : 0,
rel: 0,
showinfo: 0,
iv_load_policy: settings.annotations ? '' : 3,
autoplay: autoplay ? 1 : 0,
theme: settings.playerTheme,
wmode: settings.wmode
}
});
}
},
endpoints: {
videoClick: function(e){
var target = utils.parentUntil(e.target ? e.target : e.srcElement, 'data-ytv');
if(target){
if(target.getAttribute('data-ytv')){
// Load Video
utils.events.prevent(e);
var activeEls = settings.element.getElementsByClassName('ytv-active'),
i;
for(i=0; i<activeEls.length; i++){
activeEls[i].className="";
}
target.parentNode.className="ytv-active";
action.logic.loadVideo(target.getAttribute('data-ytv'), true);
}
}
},
playlistToggle: function(e){
var target = utils.parentUntil(e.target ? e.target : e.srcElement, 'data-ytv-playlist-toggle');
if(target && target.getAttribute('data-ytv-playlist-toggle')){
// Toggle Playlist
utils.events.prevent(e);
var lh = settings.element.getElementsByClassName('ytv-list-header')[0];
if(lh.className.indexOf('ytv-playlist-open')===-1){
lh.className += ' ytv-playlist-open';
} else {
lh.className = lh.className.replace(' ytv-playlist-open', '');
}
}
},
playlistClick: function(e){
var target = utils.parentUntil(e.target ? e.target : e.srcElement, 'data-ytv-playlist');
if(target && target.getAttribute('data-ytv-playlist')){
// Load Playlist
utils.events.prevent(e);
settings.pid = target.getAttribute('data-ytv-playlist');
target.children[1].innerHTML = 'Loading...';
utils.ajax.get( utils.endpoints.playlistInfo(settings.pid), function(res){
var lh = settings.element.getElementsByClassName('ytv-list-header')[0];
lh.className = lh.className.replace(' ytv-playlist-open', '');
prepare.selectedPlaylist(res);
});
}
}
},
bindEvents: function(){
utils.events.addEvent( settings.element, 'click', action.endpoints.videoClick );
utils.events.addEvent( settings.element, 'click', action.endpoints.playlistToggle );
utils.events.addEvent( settings.element, 'click', action.endpoints.playlistClick );
}
},
initialize = function(id, opts){
utils.deepExtend(settings, opts);
if(settings.apiKey.length===0){
alert("Missing APIkey in settings or as global vaiable.");
}
apiKey = settings.apiKey;
settings.element = (typeof id==='string') ? doc.getElementById(id) : id;
if(settings.element && (settings.user || settings.channelId || settings.playlist)){
prepare.youtube();
prepare.build();
action.bindEvents();
if (settings.playlist) {
utils.ajax.get( utils.endpoints.playlistInfo(settings.playlist), prepare.selectedPlaylist );
} else {
utils.ajax.get( utils.endpoints.userInfo(), prepare.userUploads );
}
} else console.log ('Youtube-TV Error: Missing either user, channelId, or playlist');
};
/* Public */
this.destroy = function(){
utils.events.removeEvent( settings.element, 'click', action.endpoints.videoClick );
utils.events.removeEvent( settings.element, 'click', action.endpoints.playlistToggle );
utils.events.removeEvent( settings.element, 'click', action.endpoints.playlistClick );
settings.element.className = '';
settings.element.innerHTML = '';
};
this.fullscreen = {
state: function(){
return (settings.element.className).indexOf('ytv-full') !== -1;
},
enter: function(){
if( (settings.element.className).indexOf('ytv-full') === -1 ){
settings.element.className += 'ytv-full';
}
},
exit: function(){
if( (settings.element.className).indexOf('ytv-full') !== -1 ){
settings.element.className = (settings.element.className).replace('ytv-full', '');
}
}
};
initialize(id, opts);
};
if ((typeof module !== 'undefined') && module.exports) {
module.exports = YTV;
}
if (typeof ender === 'undefined') {
this.YTV = YTV;
}
if ((typeof define === "function") && define.amd) {
define("YTV", [], function() {
return YTV;
});
}
if ((typeof jQuery !== 'undefined')) {
jQuery.fn.extend({
ytv: function(options) {
return this.each(function() {
new YTV(this.id, options);
});
}
});
}
}).call(this, window, document);
Replace this
list += '<div class="ytv-list-header">';
with
list += '<div class="ytv-list-header ytv-playlist-open">';
There is two playlist one is "list of all playlists". And other is "list of videos in a playlist".
"ytv-playlist-open" indicate the open status for "list of all playlist". So when it is added it will close "videos in a playlist" and show "list of all playlist" which you want to show there.

Javascript works in body but not in jquery side menus w/ no console errors

I'm using the jpanelmenu plugin, but this goes for the first four of the jquery side menus on this list. www.jqueryscript.net/tags.php?/side%20menu/
The scripts work fine in the body of the page. When I move the markup
<div class="ui-widget">
<input id="tags" placeholder="Search"></input>
</div>
of this autocomplete search
<script type="text/javascript">
jQuery(function() {
var availableTags = [
"Comedy",
"Music",
"Radio"
];
jQuery( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
to the side menu like this
<div class="menu-trigger-selector"><img src="https://lh3.googleusercontent.com/-G1THV0EXgLY/VQgWdKfzIvI/AAAAAAAAAJg/_AtOhuTN9JI/s28-no/hamburger-menu-icon.png" alt="Menu Button" title="Menu Button"></div>
<div id="menu-selector" style="display:none;">
<ul class="info">
<li id="about" class="noselect">Home</li>
<li id="faq" class="noselect">About</li>
<li id="contribute" class="noselect">Contact</li>
</ul>
<ul class="login-register">
<li id="login" class="noselect">Login</li>
<li id="register" class="noselect">Register</li>
</ul>
<div class="ui-widget">
<input id="tags" placeholder="Search"></input>
</div>
<ul class="podcast-list">
<li>Main1
<ul class="podcasts">
<li>Sub</li>
<li>Sub</li>
<li>Sub</li>
<li>Sub</li>
</ul>
</li>
</ul>
</div>
<div class="container">
...
</div>
it stops functioning. The input box shows up, but the autocomplete results don't. I'm using drupal, with a bootstrap subtheme, and I think this may be playing a role. I have to replace $( with jQuery( in every script because of some conflict that I don't understand. I'm loading the scripts in this order:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="../drup/misc/jquery.once.js?v=1.2"></script>
<script src="../drup/misc/drupal.js?nmk3bg"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<!-- <?php print $scripts; ?> -->
<!-- Navigation -->
<script type="text/javascript">
/**
*
* jPanelMenu 1.4.1 (http://jpanelmenu.com)
* By Anthony Colangelo (http://acolangelo.com)
*
* */
(function($){
$.jPanelMenu = function(options) {
if ( typeof(options) == "undefined" || options == null ) { options = {}; };
var jP = {
options: $.extend({
menu: '#menu',
panel: 'body',
trigger: '.menu-trigger',
excludedPanelContent: 'style, script',
clone: true,
keepEventHandlers: false,
direction: 'left',
openPosition: '250px',
animated: true,
closeOnContentClick: true,
keyboardShortcuts: [
{
code: 27,
open: false,
close: true
},
{
code: 37,
open: false,
close: true
},
{
code: 39,
open: true,
close: true
},
{
code: 77,
open: true,
close: true
}
],
duration: 150,
openDuration: options.duration || 150,
closeDuration: options.duration || 150,
easing: 'ease-in-out',
openEasing: options.easing || 'ease-in-out',
closeEasing: options.easing || 'ease-in-out',
before: function(){ },
beforeOpen: function(){ },
beforeClose: function(){ },
after: function(){ },
afterOpen: function(){ },
afterClose: function(){ },
beforeOn: function(){ },
afterOn: function(){ },
beforeOff: function(){ },
afterOff: function(){ }
},options),
settings: {
transitionsSupported: 'WebkitTransition' in document.body.style ||
'MozTransition' in document.body.style ||
'msTransition' in document.body.style ||
'OTransition' in document.body.style ||
'Transition' in document.body.style
,
transformsSupported: 'WebkitTransform' in document.body.style ||
'MozTransform' in document.body.style ||
'msTransform' in document.body.style ||
'OTransform' in document.body.style ||
'Transform' in document.body.style
,
cssPrefix: '',
panelPosition: 'static',
positionUnits: 'px'
},
menu: '#jPanelMenu-menu',
panel: '.jPanelMenu-panel',
timeouts: {},
clearTimeouts: function() {
clearTimeout(jP.timeouts.open);
clearTimeout(jP.timeouts.afterOpen);
clearTimeout(jP.timeouts.afterClose);
},
setPositionUnits: function() {
var foundUnit = false,
allowedUnits = ['%','px','em']
;
for (var unitID = 0; unitID < allowedUnits.length; unitID++) {
var unit = allowedUnits[unitID];
if ( jP.options.openPosition.toString().substr(-unit.length) == unit )
{
foundUnit = true;
jP.settings.positionUnits = unit;
}
}
if ( !foundUnit ) { jP.options.openPosition = parseInt(jP.options.openPosition) + jP.settings.positionUnits }
},
computePositionStyle: function(open, string) {
var position = (open)?jP.options.openPosition:'0' + jP.settings.positionUnits;
var property = {};
if ( jP.settings.transformsSupported ) {
var direction = (open && jP.options.direction == 'right')?'-':'';
var translate = 'translate3d(' + direction + position + ',0,0)';
var transform = 'transform';
if ( string ) {
property = '';
if ( jP.settings.cssPrefix != '' ) { property = jP.settings.cssPrefix + transform + ':' + translate + ';' }
property += transform + ':' + translate + ';';
} else {
if ( jP.settings.cssPrefix != '' ) { property[jP.settings.cssPrefix + transform] = translate; }
property[transform] = translate;
}
} else {
if ( string ) {
property = '';
property = jP.options.direction + ': ' + position + ';';
} else {
property[jP.options.direction] = position;
}
}
return property;
},
setCSSPrefix: function() {
jP.settings.cssPrefix = jP.getCSSPrefix();
},
setjPanelMenuStyles: function() {
var bg = 'background:#fff',
htmlBG = $('html').css('background-color'),
bodyBG = $('body').css('background-color');
var backgroundGenerator = function(element){
var bgs = [];
$.each(['background-color','background-image','background-position','background-repeat','background-attachment','background-size','background-clip'], function(i,value){
if( element.css(value) !== '' ) {
bgs.push(value+':'+element.css(value));
}
});
return bgs.join(';');
};
if ( bodyBG !== 'transparent' && bodyBG !== "rgba(0, 0, 0, 0)") {
bg = backgroundGenerator($('body'));
} else if ( htmlBG !== 'transparent' && htmlBG !== "rgba(0, 0, 0, 0)") {
bg = backgroundGenerator($('html'));
}
if ( $('#jPanelMenu-style-master').length == 0 ) {
$('body').append('<style id="jPanelMenu-style-master">body{width:100%}.jPanelMenu,body{overflow-x:hidden}#jPanelMenu-menu{display:block;position:fixed;top:0;'+jP.options.direction+':0;height:100%;z-index:-1;overflow-x:hidden;overflow-y:scroll;-webkit-overflow-scrolling:touch}.jPanelMenu-panel{position:static;'+jP.options.direction+':0;top:0;z-index:2;width:100%;min-height:100%;' + bg + ';}</style>');
}
},
setMenuState: function(open) {
var position = (open)?'open':'closed';
$(jP.options.panel).attr('data-menu-position', position);
},
getMenuState: function() {
return $(jP.options.panel).attr('data-menu-position');
},
menuIsOpen: function() {
if ( jP.getMenuState() == 'open' ) return true;
else return false;
},
setMenuStyle: function(styles) {
$(jP.menu).css(styles);
},
setPanelStyle: function(styles) {
$(jP.panel).css(styles);
},
showMenu: function() {
jP.setMenuStyle({
display: 'block'
});
jP.setMenuStyle({
'z-index': '1'
});
},
hideMenu: function() {
jP.setMenuStyle({
'z-index': '-1'
});
jP.setMenuStyle({
display: 'none'
});
},
enableTransitions: function(duration, easing) {
var formattedDuration = duration/1000;
var formattedEasing = jP.getCSSEasingFunction(easing);
jP.disableTransitions();
$('body').append('<style id="jPanelMenu-style-transitions">.jPanelMenu-panel{' + jP.settings.cssPrefix + 'transition: all ' + formattedDuration + 's ' + formattedEasing + '; transition: all ' + formattedDuration + 's ' + formattedEasing + ';}</style>');
},
disableTransitions: function() {
$('#jPanelMenu-style-transitions').remove();
},
getCSSEasingFunction: function(name) {
switch ( name )
{
case 'linear':
return name;
break;
case 'ease':
return name;
break;
case 'ease-in':
return name;
break;
case 'ease-out':
return name;
break;
case 'ease-in-out':
return name;
break;
default:
return 'ease-in-out';
break;
}
},
getJSEasingFunction: function(name) {
switch ( name )
{
case 'linear':
return name;
break;
default:
return 'swing';
break;
}
},
getVendorPrefix: function() {
// Thanks to Lea Verou for this beautiful function. (http://lea.verou.me/2009/02/find-the-vendor-prefix-of-the-current-browser)
if('result' in arguments.callee) return arguments.callee.result;
var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/;
var someScript = document.getElementsByTagName('script')[0];
for(var prop in someScript.style)
{
if(regex.test(prop))
{
// test is faster than match, so it's better to perform
// that on the lot and match only when necessary
return arguments.callee.result = prop.match(regex)[0];
}
}
// Nothing found so far? Webkit does not enumerate over the CSS properties of the style object.
// However (prop in style) returns the correct value, so we'll have to test for
// the precence of a specific property
if('WebkitOpacity' in someScript.style) return arguments.callee.result = 'Webkit';
if('KhtmlOpacity' in someScript.style) return arguments.callee.result = 'Khtml';
return arguments.callee.result = '';
},
getCSSPrefix: function() {
var prefix = jP.getVendorPrefix();
if ( prefix != '' ) { return '-' + prefix.toLowerCase() + '-'; }
return '';
},
openMenu: function(animated) {
if ( typeof(animated) == "undefined" || animated == null ) { animated = jP.options.animated };
jP.clearTimeouts();
jP.options.before();
jP.options.beforeOpen();
jP.setMenuState(true);
jP.showMenu();
var animationChecks = {
none: (!animated)?true:false,
transitions: (animated && jP.settings.transitionsSupported)?true:false
};
if ( animationChecks.transitions || animationChecks.none ) {
if ( animationChecks.none ) jP.disableTransitions();
if ( animationChecks.transitions ) jP.enableTransitions(jP.options.openDuration, jP.options.openEasing);
var newPanelStyle = jP.computePositionStyle(true);
jP.setPanelStyle(newPanelStyle);
jP.timeouts.afterOpen = setTimeout(function(){
jP.options.after();
jP.options.afterOpen();
jP.initiateContentClickListeners();
}, jP.options.openDuration);
}
else {
var formattedEasing = jP.getJSEasingFunction(jP.options.openEasing);
var animationOptions = {};
animationOptions[jP.options.direction] = jP.options.openPosition;
$(jP.panel).stop().animate(animationOptions, jP.options.openDuration, formattedEasing, function(){
jP.options.after();
jP.options.afterOpen();
jP.initiateContentClickListeners();
});
}
},
closeMenu: function(animated) {
if ( typeof(animated) == "undefined" || animated == null ) { animated = jP.options.animated };
jP.clearTimeouts();
jP.options.before();
jP.options.beforeClose();
jP.setMenuState(false);
var animationChecks = {
none: (!animated)?true:false,
transitions: (animated && jP.settings.transitionsSupported)?true:false
};
if ( animationChecks.transitions || animationChecks.none ) {
if ( animationChecks.none ) jP.disableTransitions();
if ( animationChecks.transitions ) jP.enableTransitions(jP.options.closeDuration, jP.options.closeEasing);
var newPanelStyle = jP.computePositionStyle();
jP.setPanelStyle(newPanelStyle);
jP.timeouts.afterClose = setTimeout(function(){
jP.disableTransitions();
jP.hideMenu();
jP.options.after();
jP.options.afterClose();
jP.destroyContentClickListeners();
}, jP.options.closeDuration);
}
else {
var formattedEasing = jP.getJSEasingFunction(jP.options.closeEasing);
var animationOptions = {};
animationOptions[jP.options.direction] = 0 + jP.settings.positionUnits;
$(jP.panel).stop().animate(animationOptions, jP.options.closeDuration, formattedEasing, function(){
jP.hideMenu();
jP.options.after();
jP.options.afterClose();
jP.destroyContentClickListeners();
});
}
},
triggerMenu: function(animated) {
if ( jP.menuIsOpen() ) jP.closeMenu(animated);
else jP.openMenu(animated);
},
initiateClickListeners: function() {
$(document).on('click touchend',jP.options.trigger,function(e){
jP.triggerMenu(jP.options.animated); e.preventDefault();
});
},
destroyClickListeners: function() {
$(document).off('click touchend',jP.options.trigger,null);
},
initiateContentClickListeners: function() {
if ( !jP.options.closeOnContentClick ) return false;
$(document).on('click touchend',jP.panel,function(e){
if ( jP.menuIsOpen() ) jP.closeMenu(jP.options.animated);
e.preventDefault();
});
},
destroyContentClickListeners: function() {
if ( !jP.options.closeOnContentClick ) return false;
$(document).off('click touchend',jP.panel,null);
},
initiateKeyboardListeners: function() {
var preventKeyListeners = ['input', 'textarea', 'select'];
$(document).on('keydown',function(e){
var target = $(e.target),
prevent = false;
$.each(preventKeyListeners, function(){
if (target.is(this.toString())) {
prevent = true;
}
});
if ( prevent ) return true;
for ( mapping in jP.options.keyboardShortcuts ) {
if ( e.which == jP.options.keyboardShortcuts[mapping].code ) {
var key = jP.options.keyboardShortcuts[mapping];
if ( key.open && key.close ) { jP.triggerMenu(jP.options.animated); }
else if ( (key.open && !key.close) && !jP.menuIsOpen() ) { jP.openMenu(jP.options.animated); }
else if ( (!key.open && key.close) && jP.menuIsOpen() ) { jP.closeMenu(jP.options.animated); }
e.preventDefault();
}
}
});
},
destroyKeyboardListeners: function() {
$(document).off('keydown',null);
},
setupMarkup: function() {
$('html').addClass('jPanelMenu');
$(jP.options.panel + ' > *').not(jP.menu + ', ' + jP.options.excludedPanelContent).wrapAll('<div class="' + jP.panel.replace('.','') + '"/>');
var menu = ( jP.options.clone )?$(jP.options.menu).clone(jP.options.keepEventHandlers):$(jP.options.menu);
menu.attr('id', jP.menu.replace('#','')).insertAfter(jP.options.panel + ' > ' + jP.panel);
},
resetMarkup: function() {
$('html').removeClass('jPanelMenu');
$(jP.options.panel + ' > ' + jP.panel + ' > *').unwrap();
$(jP.menu).remove();
},
init: function() {
jP.options.beforeOn();
jP.setPositionUnits();
jP.setCSSPrefix();
jP.initiateClickListeners();
if ( Object.prototype.toString.call(jP.options.keyboardShortcuts) === '[object Array]' ) { jP.initiateKeyboardListeners(); }
jP.setjPanelMenuStyles();
jP.setMenuState(false);
jP.setupMarkup();
jP.setPanelStyle({ position: (( jP.options.animated && jP.settings.panelPosition === 'static' )?'relative':jP.settings.panelPosition) });
jP.setMenuStyle({ width: jP.options.openPosition });
jP.closeMenu(false);
jP.options.afterOn();
},
destroy: function() {
jP.options.beforeOff();
jP.closeMenu();
jP.destroyClickListeners();
if ( Object.prototype.toString.call(jP.options.keyboardShortcuts) === '[object Array]' ) { jP.destroyKeyboardListeners(); }
jP.resetMarkup();
var childrenStyles = {};
childrenStyles[jP.options.direction] = 'auto';
jP.options.afterOff();
}
};
return {
on: jP.init,
off: jP.destroy,
trigger: jP.triggerMenu,
open: jP.openMenu,
close: jP.closeMenu,
isOpen: jP.menuIsOpen,
menu: jP.menu,
getMenu: function() { return $(jP.menu); },
panel: jP.panel,
getPanel: function() { return $(jP.panel); },
setPosition: function(position) {
if ( typeof(position) == "undefined" || position == null ) {
position = jP.options.openPosition
}
jP.options.openPosition = position;
jP.setMenuStyle({ width: jP.options.openPosition });
}
};
};
})(jQuery);
</script>
<script type="text/javascript">
jQuery(function() {
var jPM = jQuery.jPanelMenu();
var jPM = jQuery.jPanelMenu({
menu: '#menu-selector',
trigger: '.menu-trigger-selector',
duration: 300
});
jPM.on();
})
</script>
<!-- Search autocomplete -->
<script type="text/javascript">
jQuery(function() {
var availableTags = [
"Comedy",
"Music",
"Radio"
];
jQuery( "#tags" ).autocomplete({
source: availableTags
});
});
</script>

Jquery plugin call methods

Hi i have this little plugin installed:
(function($) {
$.fn.tagfield = function(options) {
if (options && options.add) {
this.each(function(i, elem) {
add_tags(elem, options.add);
});
} if (options && options.remove) {
this.each(function(i, elem) {
remove_tags(elem, options.add);
});
} else {
this.each(function(i, elem) {
var initial_tags = $(elem).val();
$(elem).val('');
tagfield(this, $(elem));
$(initial_tags.split(',')).each(function(i, v) {
v = $.trim(v);
if (v !== '') add_tags(elem, v);
})
});
}
};
var KEYS = {
"enter": "\r".charCodeAt(0),
"space": " ".charCodeAt(0),
"comma": 188,
"backspace": 8
};
var tagfield_id_for = function(real_input) {
return $(real_input).attr('id') + '_tagfield';
};
var add_tags = function(real_input, text) {
remove_tags(real_input, text);
var tag = $('<span class="tag">').append('<span class="text">' + text +'</span>'),
close = $('<a class="close" href="#">X</a>');
close.click(function(e) {
remove_tags(real_input, text);
});
tag.append(close);
$('#' + tagfield_id_for(real_input) + " .tags").append(tag);
real_input = $(real_input);
real_input.val(($.trim(real_input.val()) === '' ? [] : real_input.val().split(',')).concat([text]).join(','));
};
var remove_tags = function(real_input, text) {
$('#' + tagfield_id_for(real_input) + " .tags .tag").each(function(i, v) {
v = $(v);
if (v.find('.text').html() === text) {
v.remove();
real_input = $(real_input);
var tags = $(real_input.val().split(',')).filter(function(i, v) {
return v !== text;
});
real_input.val(Array.prototype.join.call(tags));
}
});
};
var tagfield = function(real_input, elem) {
var tagfield = $('<div class="tagfield">').attr('id', tagfield_id_for(real_input)),
input = $('<input type="text"/>'),
buffer = $('<span class="buffer">'),
tags = $('<span class="tags">');
tagfield.append(tags);
tagfield.append(buffer);
tagfield.append(input);
tagfield.click(function(e) {
input.focus();
});
var check_add_tag = function() {
if (buffer.html()) {
var tag_text = buffer.html();
buffer.html('');
add_tags(real_input, tag_text);
}
};
var add_tag = function(text) {
};
input.keydown(function(e) {
if (e.which === KEYS.enter || e.which === KEYS.space || e.which === KEYS.comma) {
e.preventDefault();
check_add_tag();
}
if (e.which === KEYS.backspace) {
if (buffer.html() === "") {
remove_tags(real_input, tagfield.find('.tag').last().find('.text').html());
} else {
var s = buffer.html();
buffer.html(s.slice(0, s.length-1));
}
}
});
input.blur(check_add_tag);
input.keyup(function(e) {
buffer.append(input.val());
input.val('');
});
$(real_input).hide().after(tagfield);
};
})(jQuery);
does anyone can show me how can i call the methods add_tags() and remove_tags() ?
thanks
$("selector").tagfield({remove:someobject});
$("selector").tagfield({add:someobject});
but the "remove" thing will not work i think, since the second "if" in fn.tagfield watches for "options.remove" but removes the "options.add" ...

Categories

Resources