Jquery conflict between two versions - javascript

Ok i have site with old version of jquery, then i imported modul, where i have newer version of jquery, in my modul page i have this line of jquery
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
Somehow i have conflict. I cant remove old version from header cuz some function dont work, in the other side in my module page if i remove newer version spinner function dont work. I cant use both jquery versions in same time. is there some way how to resolve this conflict.
Code where i have error is: In this script i need older version not before loaded new version jquery-1.10.2.js
var notice = new Array();
$(document).ready( function() {
/*setTimeout(function(){ $(".notice").fadeTo('slow',1), 500; });
setTimeout(function(){ $(".notice").fadeTo('slow',0.4); }, 1500);*/
/*setTimeout(function(){
$(".notice").animate( { backgroundColor: '#B8B8B8' }, 1000)
});*/
setTimeout(function(){
$(".notice").animate( { backgroundColor: '#e0e0e0' }, 1000)
});
$.safetynet({
message : isDirtyWarning
});
});
/**
* Funkcija ce Sve vrednosti Combo Boksa upisati u hidden polje razdvojeno
* zarezom
*
* #param hidden_field_id
* #return
*/
function ComboFieldsToValue(combo_selector, hidden_field_id) {
var vrednosti = "";
$(combo_selector + ' option').each( function() {
vrednosti += $(this).val() + ',';
});
$(hidden_field_id).attr( {
value :vrednosti.substring(0, vrednosti.length - 1)
});
// alert($(hidden_field_id).attr("value"));
}
/**
* Proverava da li Combo ima item sa zadatom vrednoscu
* Vraca true ako ima, false ako nema
* #param combo_selector
* #param key
* #return
*/
function IsItemInCombo(combo_selector, key) {
var is_in_combo = false;
$(combo_selector + ' option').each( function() {
if ($(this).val() == key) {
is_in_combo = true;
}
});
return is_in_combo;
}
/**
* Potrda brisanja
* #param link
* #return
*/
function PotvrdiBrisanje(link, str) {
if(str == "") str = "Potvrdi brisanje?";
if (confirm("" + str)) {
document.location = link;
}
}
function ajaxPotvrdiBrisanje(link, str, autoconfirm, flexi_id) {
if(str == "") str = "Potvrdi brisanje?";
if(autoconfirm == "") autoconfirm = false;
if(flexi_id == "" || !flexi_id) flexi_id = 'flex1';
if (autoconfirm || confirm("" + str)) {
$.ajax({
url: link,
async : false,
success: function(data) {
if (data.substr(0, 4) == "msg:") {
notice[notice.length] = data.substr(4,data.length);
}
}
});
}
return false;
}
function addToNotice(data)
{
if (data.substr(0, 4) == "msg:") {
notice[notice.length] = data.substr(4,data.length);
}
}
function PrikaziNotice() {
if (notice.length == 0) return;
$('p.flexy_notice').html('');
$('p.flexy_notice').css({ backgroundColor: '#FB2D2B' });
$('p.flexy_notice').hide('');
/*
* Uknjamoi osmnovni notce
*
*/
if ($('.notice').length != 0) {
$('.notice').hide();
}
html = "";
for ( var i in notice ) {
html += '<p>' + notice[i] + '</p>';
}
$('p.flexy_notice').html(html);
$('p.flexy_notice').show();
$(".flexy_notice").animate( { backgroundColor: '#e0e0e0' }, 1000);
notice = new Array();
}
function reloadFlexi() { $("#flex1").flexReload(); }
function ShowAudit(id) {
$(".audit_" + id).toggle();
}
function setDirtyTiny(){
$.safetynet.raiseChange($('textarea'));
}
Can someone explain me how to adjust this js file

If you need to run two versions of jquery, you can use noconflict.
Example:
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
newJquery = jQuery.noConflict(true);
newJquery(document).ready( function() {
...
...

Here is a blog dealing with this problem:
http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/

Just add this to your html page in which the conflict occurs:
<script>
$.noConflict();
</script>

Related

Loading two similar scripts twice dosn't work

i have this javascript that I called cookiebar.js, it shows a sticky bar message for cookies, (source code)
(function (context) {
"use strict";
var win = context,
doc = win.document;
var global_instance_name = "cbinstance";
function contentLoaded(win, fn) {
var done = false,
top = true,
doc = win.document,
root = doc.documentElement,
add = doc.addEventListener ? "addEventListener" : "attachEvent",
rem = doc.addEventListener ? "removeEventListener" : "detachEvent",
pre = doc.addEventListener ? "" : "on",
init = function (e) {
if (e.type == "readystatechange" && doc.readyState != "complete") return;
(e.type == "load" ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function () {
try {
root.doScroll("left");
} catch (e) {
setTimeout(poll, 50);
return;
}
init("poll");
};
if (doc.readyState == "complete") fn.call(win, "lazy");
else {
if (doc.createEventObject && root.doScroll) {
try {
top = !win.frameElement;
} catch (e) {}
if (top) poll();
}
doc[add](pre + "DOMContentLoaded", init, false);
doc[add](pre + "readystatechange", init, false);
win[add](pre + "load", init, false);
}
}
var Cookies = {
get: function (key) {
return decodeURIComponent(doc.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
set: function (key, val, end, path, domain, secure) {
if (!key || /^(?:expires|max\-age|path|domain|secure)$/i.test(key)) {
return false;
}
var expires = "";
if (end) {
switch (end.constructor) {
case Number:
expires = end === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + end;
break;
case String:
expires = "; expires=" + end;
break;
case Date:
expires = "; expires=" + end.toUTCString();
break;
}
}
doc.cookie = encodeURIComponent(key) + "=" + encodeURIComponent(val) + expires + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "") + (secure ? "; secure" : "");
return true;
},
has: function (key) {
return new RegExp("(?:^|;\\s*)" + encodeURIComponent(key).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=").test(doc.cookie);
},
remove: function (key, path, domain) {
if (!key || !this.has(key)) {
return false;
}
doc.cookie = encodeURIComponent(key) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "");
return true;
},
};
var Utils = {
merge: function () {
var obj = {},
i = 0,
al = arguments.length,
key;
if (0 === al) {
return obj;
}
for (; i < al; i++) {
for (key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
},
str2bool: function (str) {
str = "" + str;
switch (str.toLowerCase()) {
case "false":
case "no":
case "0":
case "":
return false;
default:
return true;
}
},
fade_in: function (el) {
if (el.style.opacity < 1) {
el.style.opacity = (parseFloat(el.style.opacity) + 0.05).toFixed(2);
win.setTimeout(function () {
Utils.fade_in(el);
}, 50);
}
},
get_data_attribs: function (script) {
var data = {};
if (Object.prototype.hasOwnProperty.call(script, "dataset")) {
data = script.dataset;
} else {
var attribs = script.attributes;
var key;
for (key in attribs) {
if (Object.prototype.hasOwnProperty.call(attribs, key)) {
var attr = attribs[key];
if (/^data-/.test(attr.name)) {
var camelized = Utils.camelize(attr.name.substr(5));
data[camelized] = attr.value;
}
}
}
}
return data;
},
normalize_keys: function (options_object) {
var camelized = {};
for (var key in options_object) {
if (Object.prototype.hasOwnProperty.call(options_object, key)) {
var camelized_key = Utils.camelize(key);
camelized[camelized_key] = options_object[camelized_key] ? options_object[camelized_key] : options_object[key];
}
}
return camelized;
},
camelize: function (str) {
var separator = "-",
match = str.indexOf(separator);
while (match != -1) {
var last = match === str.length - 1,
next = last ? "" : str[match + 1],
upnext = next.toUpperCase(),
sep_substr = last ? separator : separator + next;
str = str.replace(sep_substr, upnext);
match = str.indexOf(separator);
}
return str;
},
find_script_by_id: function (id) {
var scripts = doc.getElementsByTagName("script");
for (var i = 0, l = scripts.length; i < l; i++) {
if (id === scripts[i].id) {
return scripts[i];
}
}
return null;
},
};
var script_el_invoker = Utils.find_script_by_id("cookiebanner");
var Cookiebanner = (context.Cookiebanner = function (opts) {
this.init(opts);
});
Cookiebanner.prototype = {
cookiejar: Cookies,
init: function (opts) {
this.inserted = false;
this.closed = false;
this.test_mode = false;
var default_text = "This site uses cookies.";
var default_link = "Detail";
this.default_options = {
cookie: "cookiebanner-accepted",
closeText: "✖",
cookiePath: "/",
debug: false,
expires: Infinity,
zindex: 255,
mask: false,
maskOpacity: 0.5,
maskBackground: "#000",
height: "auto",
minHeight: "21px",
bg: "#000",
fg: "#ddd",
link: "#aaa",
position: "bottom",
message: default_text,
linkmsg: default_link,
moreinfo: "http://www.examplesite123.com/cookie-policy/",
effect: null,
fontSize: "14px",
fontFamily: "arial, sans-serif",
instance: global_instance_name,
textAlign: "center",
acceptOnScroll: true,
};
this.options = this.default_options;
this.script_el = script_el_invoker;
if (this.script_el) {
var data_options = Utils.get_data_attribs(this.script_el);
this.options = Utils.merge(this.options, data_options);
}
if (opts) {
opts = Utils.normalize_keys(opts);
this.options = Utils.merge(this.options, opts);
}
global_instance_name = this.options.instance;
this.options.zindex = parseInt(this.options.zindex, 10);
this.options.mask = Utils.str2bool(this.options.mask);
if ("string" === typeof this.options.expires) {
if ("function" === typeof context[this.options.expires]) {
this.options.expires = context[this.options.expires];
}
}
if ("function" === typeof this.options.expires) {
this.options.expires = this.options.expires();
}
if (this.script_el) {
this.run();
}
},
log: function () {
if ("undefined" !== typeof console) {
console.log.apply(console, arguments);
}
},
run: function () {
if (!this.agreed()) {
var self = this;
contentLoaded(win, function () {
self.insert();
});
}
},
build_viewport_mask: function () {
var mask = null;
if (true === this.options.mask) {
var mask_opacity = this.options.maskOpacity;
var bg = this.options.maskBackground;
var mask_markup =
'<div id="cookiebanner-mask" style="' +
"position:fixed;top:0;left:0;width:100%;height:100%;" +
"background:" +
bg +
";zoom:1;filter:alpha(opacity=" +
mask_opacity * 100 +
");opacity:" +
mask_opacity +
";" +
"z-index:" +
this.options.zindex +
';"></div>';
var el = doc.createElement("div");
el.innerHTML = mask_markup;
mask = el.firstChild;
}
return mask;
},
agree: function () {
this.cookiejar.set(this.options.cookie, 1, this.options.expires, this.options.cookiePath);
return true;
},
agreed: function () {
return this.cookiejar.has(this.options.cookie);
},
close: function () {
if (this.inserted) {
if (!this.closed) {
if (this.element) {
this.element.parentNode.removeChild(this.element);
}
if (this.element_mask) {
this.element_mask.parentNode.removeChild(this.element_mask);
}
this.closed = true;
}
}
return this.closed;
},
agree_and_close: function () {
this.agree();
return this.close();
},
cleanup: function () {
this.close();
return this.unload();
},
unload: function () {
if (this.script_el) {
this.script_el.parentNode.removeChild(this.script_el);
}
context[global_instance_name] = undefined;
return true;
},
insert: function () {
this.element_mask = this.build_viewport_mask();
var zidx = this.options.zindex;
if (this.element_mask) {
zidx += 1;
}
var el = doc.createElement("div");
el.className = "cookiebanner";
el.style.position = "fixed";
el.style.left = 0;
el.style.right = 0;
el.style.height = this.options.height;
el.style.minHeight = this.options.minHeight;
el.style.zIndex = zidx;
el.style.background = this.options.bg;
el.style.color = this.options.fg;
el.style.lineHeight = el.style.minHeight;
el.style.padding = "5px 16px";
el.style.fontFamily = this.options.fontFamily;
el.style.fontSize = this.options.fontSize;
el.style.textAlign = this.options.textAlign;
if ("top" === this.options.position) {
el.style.top = 0;
} else {
el.style.bottom = 0;
}
el.innerHTML = '<div class="cookiebanner-close" style="float:right;padding-left:5px;">' + this.options.closeText + "</div>" + "<span>" + this.options.message + " <a>" + this.options.linkmsg + "</a></span>";
this.element = el;
var el_a = el.getElementsByTagName("a")[0];
el_a.href = this.options.moreinfo;
el_a.target = "_blank";
el_a.style.textDecoration = "none";
el_a.style.color = this.options.link;
var el_x = el.getElementsByTagName("div")[0];
el_x.style.cursor = "pointer";
function on(el, ev, fn) {
var add = el.addEventListener ? "addEventListener" : "attachEvent",
pre = el.addEventListener ? "" : "on";
el[add](pre + ev, fn, false);
}
var self = this;
on(el_x, "click", function () {
self.agree_and_close();
});
if (this.element_mask) {
on(this.element_mask, "click", function () {
self.agree_and_close();
});
doc.body.appendChild(this.element_mask);
}
if (this.options.acceptOnScroll) {
on(window, "scroll", function () {
self.agree_and_close();
});
}
doc.body.appendChild(this.element);
this.inserted = true;
if ("fade" === this.options.effect) {
this.element.style.opacity = 0;
Utils.fade_in(this.element);
} else {
this.element.style.opacity = 1;
}
},
};
if (script_el_invoker) {
if (!context[global_instance_name]) {
context[global_instance_name] = new Cookiebanner();
}
}
})(window);
I load it in this way in functions.php in Wordpress:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
Now i duplicate the same javascript code and i called it stickybar.js. I add some modifications, also change class with name "stickybar":
The code of the stickybar.js is here (i pasted it in jsfiddle because there is too much text for stackoverflow)
Then i show this second bar (stickybar.js) only on mobile device and after 8 second with this CSS:
.stickybar { display: none; }
#media only screen and (max-device-width:480px) {
.stickybar {
display: block;
animation: cssAnimation 0s 8s forwards;
visibility: hidden;
}
#keyframes cssAnimation {
to { visibility: visible; }
}
}
I load it in Wordpress with this code in functions.php:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
It works fine.
If i load one by one of this codes, they work fine.
The problem is that when i load the two scripts together in this way in functions.php, only the first works:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
How can i load the two scripts together?
The comment thread on this question is semantically correct, you can only have one instance of each html id attribute, they must be unique, and your find_script_by_id methods are both searching for the same thing.
However, you're doing what's generally called "baking in" the scripts into your header which is at best, a faux pas, at least as far as WordPress is concerned. Properly Enqueueing Scripts (and styles) is very easy in WordPress, and your future self, web clients, and other people who look at your code will thank you for doing it.
It's not unlike how you're "baking in" the scripts now:
function wpb_hook_javascript() {
?>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/cookiebar.js"></script>
<script defer type="text/javascript" id="cookiebanner" src="https://www.examplesite123.com/stickybar.js"></script>
<?php
}
add_action('wp_head', 'wpb_hook_javascript');
But with a few things changed:
function enqueue_my_scripts(){
wp_enqueue_script( 'cookie-bar', 'https://www.examplesite123.com/cookiebar.js', array(), '1.0', true );
wp_enqueue_script( 'sticky-bar', 'https://www.examplesite123.com/stickybar.js', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );
Namely, it uses the wp_enqueue_script() function on the wp_enqueue_scripts hook. This lets you defer the script to the footer, load in the header, add version numbers to prevent caching issues, add dependencies, allows you to dynamically add/remove them programatically,gives them unique ID's based on the handle, and much more. (You do still need to update your find_script_by_id functions to use these new handles instead cookie-bar, sticky-bar, change the global_instance_name, etc. (more on that in a second)
With that said, if the .js files are on your server, you'll want to use site_url(), plugins_url(), get_stylesheet_directory_uri(), or similar functions to grab the URL of the file instead of typing it out. If you're using a remote resource, don't worry about it, but if they're on you're site, you should swap out the baked in version for that so you don't have issues if you ever move your site, and it allows you easier methods to edit the version to prevent caching problems if you change them.
Back to your variables, you may also want to replace your find_script_by_id type functions with document.currentScript instead, to allow them to be more abstract and not rely on typo/duplicate prone element IDs, and instead reference the currently running <script> tag.

Uncaught ReferenceError: jQuery is not defined

i am getting an error in console as Uncaught ReferenceError: jQuery is not defined(anonymous function). below is my code
yii = (function ($) {
var pub = {
/**
* List of JS or CSS URLs that can be loaded multiple times via AJAX requests. Each script can be represented
* as either an absolute URL or a relative one.
*/
reloadableScripts: [],
/**
* The selector for clickable elements that need to support confirmation and form submission.
*/
clickableSelector: 'a, button, input[type="submit"], input[type="button"], input[type="reset"], input[type="image"]',
/**
* The selector for changeable elements that need to support confirmation and form submission.
*/
changeableSelector: 'select, input, textarea',
/**
* #return string|undefined the CSRF parameter name. Undefined is returned if CSRF validation is not enabled.
*/
getCsrfParam: function () {
return $('meta[name=csrf-param]').attr('content');
},
/**
* #return string|undefined the CSRF token. Undefined is returned if CSRF validation is not enabled.
*/
getCsrfToken: function () {
return $('meta[name=csrf-token]').attr('content');
},
/**
* Sets the CSRF token in the meta elements.
* This method is provided so that you can update the CSRF token with the latest one you obtain from the server.
* #param name the CSRF token name
* #param value the CSRF token value
*/
setCsrfToken: function (name, value) {
$('meta[name=csrf-param]').attr('content', name);
$('meta[name=csrf-token]').attr('content', value)
},
/**
* Updates all form CSRF input fields with the latest CSRF token.
* This method is provided to avoid cached forms containing outdated CSRF tokens.
*/
refreshCsrfToken: function () {
var token = pub.getCsrfToken();
if (token) {
$('form input[name="' + pub.getCsrfParam() + '"]').val(token);
}
},
/**
* Displays a confirmation dialog.
* The default implementation simply displays a js confirmation dialog.
* You may override this by setting `yii.confirm`.
* #param message the confirmation message.
* #param ok a callback to be called when the user confirms the message
* #param cancel a callback to be called when the user cancels the confirmation
*/
confirm: function (message, ok, cancel) {
if (confirm(message)) {
!ok || ok();
} else {
!cancel || cancel();
}
},
/**
* Handles the action triggered by user.
* This method recognizes the `data-method` attribute of the element. If the attribute exists,
* the method will submit the form containing this element. If there is no containing form, a form
* will be created and submitted using the method given by this attribute value (e.g. "post", "put").
* For hyperlinks, the form action will take the value of the "href" attribute of the link.
* For other elements, either the containing form action or the current page URL will be used
* as the form action URL.
*
* If the `data-method` attribute is not defined, the `href` attribute (if any) of the element
* will be assigned to `window.location`.
*
* Starting from version 2.0.3, the `data-params` attribute is also recognized when you specify
* `data-method`. The value of `data-params` should be a JSON representation of the data (name-value pairs)
* that should be submitted as hidden inputs. For example, you may use the following code to generate
* such a link:
*
* ```php
* use yii\helpers\Html;
* use yii\helpers\Json;
*
* echo Html::a('submit', ['site/foobar'], [
* 'data' => [
* 'method' => 'post',
* 'params' => [
* 'name1' => 'value1',
* 'name2' => 'value2',
* ],
* ],
* ];
* ```
*
* #param $e the jQuery representation of the element
*/
handleAction: function ($e) {
var method = $e.data('method'),
$form = $e.closest('form'),
action = $e.attr('href'),
params = $e.data('params');
if (method === undefined) {
if (action && action != '#') {
window.location = action;
} else if ($e.is(':submit') && $form.length) {
$form.trigger('submit');
}
return;
}
var newForm = !$form.length;
if (newForm) {
if (!action || !action.match(/(^\/|:\/\/)/)) {
action = window.location.href;
}
$form = $('<form method="' + method + '"></form>');
$form.attr('action', action);
var target = $e.attr('target');
if (target) {
$form.attr('target', target);
}
if (!method.match(/(get|post)/i)) {
$form.append('<input name="_method" value="' + method + '" type="hidden">');
method = 'POST';
}
if (!method.match(/(get|head|options)/i)) {
var csrfParam = pub.getCsrfParam();
if (csrfParam) {
$form.append('<input name="' + csrfParam + '" value="' + pub.getCsrfToken() + '" type="hidden">');
}
}
$form.hide().appendTo('body');
}
var activeFormData = $form.data('yiiActiveForm');
if (activeFormData) {
// remember who triggers the form submission. This is used by yii.activeForm.js
activeFormData.submitObject = $e;
}
// temporarily add hidden inputs according to data-params
if (params && $.isPlainObject(params)) {
$.each(params, function (idx, obj) {
$form.append('<input name="' + idx + '" value="' + obj + '" type="hidden">');
});
}
var oldMethod = $form.attr('method');
$form.attr('method', method);
var oldAction = null;
if (action && action != '#') {
oldAction = $form.attr('action');
$form.attr('action', action);
}
$form.trigger('submit');
if (oldAction != null) {
$form.attr('action', oldAction);
}
$form.attr('method', oldMethod);
// remove the temporarily added hidden inputs
if (params && $.isPlainObject(params)) {
$.each(params, function (idx, obj) {
$('input[name="' + idx + '"]', $form).remove();
});
}
if (newForm) {
$form.remove();
}
},
getQueryParams: function (url) {
var pos = url.indexOf('?');
if (pos < 0) {
return {};
}
var qs = url.substring(pos + 1).split('&');
for (var i = 0, result = {}; i < qs.length; i++) {
qs[i] = qs[i].split('=');
result[decodeURIComponent(qs[i][0])] = decodeURIComponent(qs[i][1]);
}
return result;
},
initModule: function (module) {
if (module.isActive === undefined || module.isActive) {
if ($.isFunction(module.init)) {
module.init();
}
$.each(module, function () {
if ($.isPlainObject(this)) {
pub.initModule(this);
}
});
}
},
init: function () {
initCsrfHandler();
initRedirectHandler();
initScriptFilter();
initDataMethods();
}
};
function initRedirectHandler() {
// handle AJAX redirection
$(document).ajaxComplete(function (event, xhr, settings) {
var url = xhr.getResponseHeader('X-Redirect');
if (url) {
window.location = url;
}
});
}
function initCsrfHandler() {
// automatically send CSRF token for all AJAX requests
$.ajaxPrefilter(function (options, originalOptions, xhr) {
if (!options.crossDomain && pub.getCsrfParam()) {
xhr.setRequestHeader('X-CSRF-Token', pub.getCsrfToken());
}
});
pub.refreshCsrfToken();
}
function initDataMethods() {
var handler = function (event) {
var $this = $(this),
method = $this.data('method'),
message = $this.data('confirm');
if (method === undefined && message === undefined) {
return true;
}
if (message !== undefined) {
pub.confirm(message, function () {
pub.handleAction($this);
});
} else {
pub.handleAction($this);
}
event.stopImmediatePropagation();
return false;
};
// handle data-confirm and data-method for clickable and changeable elements
$(document).on('click.yii', pub.clickableSelector, handler)
.on('change.yii', pub.changeableSelector, handler);
}
function initScriptFilter() {
var hostInfo = location.protocol + '//' + location.host;
var loadedScripts = $('script[src]').map(function () {
return this.src.charAt(0) === '/' ? hostInfo + this.src : this.src;
}).toArray();
$.ajaxPrefilter('script', function (options, originalOptions, xhr) {
if (options.dataType == 'jsonp') {
return;
}
var url = options.url.charAt(0) === '/' ? hostInfo + options.url : options.url;
if ($.inArray(url, loadedScripts) === -1) {
loadedScripts.push(url);
} else {
var found = $.inArray(url, $.map(pub.reloadableScripts, function (script) {
return script.charAt(0) === '/' ? hostInfo + script : script;
})) !== -1;
if (!found) {
xhr.abort();
}
}
});
$(document).ajaxComplete(function (event, xhr, settings) {
var styleSheets = [];
$('link[rel=stylesheet]').each(function () {
if ($.inArray(this.href, pub.reloadableScripts) !== -1) {
return;
}
if ($.inArray(this.href, styleSheets) == -1) {
styleSheets.push(this.href)
} else {
$(this).remove();
}
})
});
}
return pub;
})(jQuery);
jQuery(document).ready(function () {
yii.initModule(yii);
});
what is the problem? am i missing something. i am not very good in javascript. this js file yii.activeForm.js is in web/assets/b807742
because of this error modal is not working
You need to insert:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
As the first script on your page. This is the jQuery library that you need to get this to work. It is one of the dependencies.

How to create a plugin to add attachment or file in rich text editor of Adobe CQ 5?

I need help in creating a plugin for rich text editor in Adobe cq 5 to add an image, pdf, video, ppt or any file into rich text editor.
The existing rte plugins that are available are findreplace, undo, spellcheck, table etc
How to create a plugin to add a file to rich text editor?
The plugins are an ext js files. Appreciate if any one can suggest answer. It will be of great help.
Thanks
I added a custom drop down into my RTE. It was used to add values to the editor on selecting values from it. I think this might help you solve your issue because similarly you can create your required plugin.
Please refer comments next to the methods for your reference.
/**
* Placeholder Plugin
*/
var keyvalueEnteries = [];
var newText;
var doc;
var range
CUI.rte.plugins.PlaceholderPlugin = new Class({
toString: "PlaceholderPlugin",
extend: CUI.rte.plugins.Plugin,
/**
* #private
*/
cachedFormats: null,
/**
* #private
*/
formatUI: null,
getFeatures: function() {
return [ "Myparaformat" ];
},
/**
* #private
*
*/
getKeys: function() {
var com = CUI.rte.Common;
if (this.cachedFormats == null) {
this.cachedFormats = this.config.formats || { };
com.removeJcrData(this.cachedFormats);
this.cachedFormats = com.toArray(this.cachedFormats, "tag", "description");
}
return this.cachedFormats;
},
initializeUI: function(tbGenerator) {
var plg = CUI.rte.plugins;
var ui = CUI.rte.ui;
if (this.isFeatureEnabled("placeHolder")) {
this.formatUI = tbGenerator.createParaFormatter("placeHolder", this,null,this.getKeys());
tbGenerator.addElement("placeHolder", plg.Plugin.SORT_PARAFORMAT, this.formatUI,
10);
}
},
notifyPluginConfig: function(pluginConfig) { //This function gets executed once on load of RTE for the first time
var url = pluginConfig.sourceURL;
keyvalueEnteries = CQ.HTTP.eval(url);
keyvalueEnteries = JSON.stringify(keyvalueEnteries);
if(keyvalueEnteries == undefined){
keyvalueEnteries = '[{"key":"","value":"None"}]';
}
pluginConfig = pluginConfig || { };
//creating JSON sttructure
var placeholderJSON = '{"formats":' + keyvalueEnteries + '}';
var placeHolderVals = eval('(' + placeholderJSON + ')');
var defaults = placeHolderVals;
if (pluginConfig.formats) {
delete defaults.formats;
}
CUI.rte.Utils.applyDefaults(pluginConfig, defaults);
this.config = pluginConfig;
},
execute: function(cmd) { // This function gets executed when there is change in the state of custom plugin/drop down
if (this.formatUI) {
var formatId = this.formatUI.getSelectedFormat();
if (formatId && range != undefined) {
var placeholderElement = "";
if(formatId == 'none' && range.collapsed == false){//checks if None is selected in placeholder and the text is selected
range.deleteContents();
}else if(formatId != 'none'){
placeholderElement = document.createTextNode(" ${" + formatId + "} ");
range.insertNode(placeholderElement); //INSERTS PLACEHOLDER AT CURRENT CARET LOCATION
range.setStartAfter(placeholderElement);//INSERTS CURSOR AT THE END OF CURRENT PLACEHOLDER IF PLACEHOLDER IS SELECTED AGAIN
}
}
}
},
updateState: function(selDef) { // This function gets executed on click on the editor space in RTE
doc = selDef.editContext.doc; //GET THE DOCUMENT INSIDE THE IFRAME
range = doc.getSelection().getRangeAt(0); //GETS CURRENT CARET POSITION
}
});
//register plugin
CUI.rte.plugins.PluginRegistry.register("placeholder",
CUI.rte.plugins.PlaceholderPlugin);
CUI.rte.ui.ext.ParaFormatterImpl = new Class({
toString: "ParaFormatterImpl",
extend: CUI.rte.ui.TbParaFormatter,
// Interface implementation ------------------------------------------------------------
addToToolbar: function(toolbar) {
var com = CUI.rte.Common;
this.toolbar = toolbar;
if (com.ua.isIE) {
// the regular way doesn't work for IE anymore with Ext 3.1.1, hence working
// around
var helperDom = document.createElement("span");
helperDom.innerHTML = "<select class=\"x-placeholder-select\">"
+ this.createFormatOptions() + "</select>";
this.formatSelector = CQ.Ext.get(helperDom.childNodes[0]);
} else {
this.formatSelector = CQ.Ext.get(CQ.Ext.DomHelper.createDom({
tag: "select",
cls: "x-placeholder-select",
html: this.createFormatOptions()
}));
}
this.initializeSelector();
toolbar.add(
CQ.I18n.getMessage("Placeholder"), // Type the name you want to appear in RTE for the custom plugin /drop down
" ",
this.formatSelector.dom);
},
/**
* Creates HTML code for rendering the options of the format selector.
* #return {String} HTML code containing the options of the format selector
* #private
*/
createFormatOptions: function() {
var htmlCode = "";
if (this.formats) {
var formatCnt = this.formats.length;
htmlCode += "<option value='none'>None</option>";
for (var f = 0; f < formatCnt; f++) {
var text = this.formats[f].text;
htmlCode += "<option value=\"" + this.formats[f].value + "\">" + text
+ "</option>";
}
}
return htmlCode;
},
createToolbarDef: function() {
return {
"xtype": "panel",
"itemId": this.id,
"html": "<select class=\"x-placeholder-select\">"
+ this.createFormatOptions() + "</select>",
"listeners": {
"afterrender": function() {
var item = this.toolbar.items.get(this.id);
if (item && item.body) {
this.formatSelector = CQ.Ext.get(item.body.dom.childNodes[0]);
this.initializeSelector();
}
},
"scope": this
}
};
},
initializeSelector: function() {
this.formatSelector.on('change', function() {
var format = this.formatSelector.dom.value;
if (format.length > 0) {
this.plugin.execute(this.id);
}
}, this);
this.formatSelector.on('focus', function() {
this.plugin.editorKernel.isTemporaryBlur = true;
}, this);
// fix for a Firefox problem that adjusts the combobox' height to the height
// of the largest entry
this.formatSelector.setHeight(20);
},
getSelectorDom: function() {
return this.formatSelector.dom;
},
getSelectedFormat: function() {
var format;
if (this.formatSelector) {
format = this.formatSelector.dom.value;
if (format.length > 0) {
return format;
}
} else {
var item = this.toolbar.items.get(this.id);
if (item.getValue()) {
return item;
}
}
return null;
},
selectFormat: function(formatToSelect, auxRoot, formatCnt, noFormatCnt) {
var indexToSelect = -1;
var selectorDom = this.formatSelector.dom;
if ((formatToSelect != null) && (formatCnt == 1) && (noFormatCnt == 0)) {
var options = selectorDom.options;
for (var optIndex = 0; optIndex < options.length; optIndex++) {
var optionToCheck = options[optIndex];
if (optionToCheck.value == formatToSelect) {
indexToSelect = optIndex;
break;
}
}
}
selectorDom.disabled = (noFormatCnt > 0) && (auxRoot == null);
selectorDom.selectedIndex = indexToSelect;
}
});

How do I integrate requirejs?

I have a file in my ASP.NET MVC project which depends on Jquery:
// namespace pattern
var diem = diem || {};
diem .defineNamespace = function(ns_string) {
var parts = ns_string.split('.');
var parent = diem ;
var i;
if(parts[0] === "diem ") {
parts = parts.slice(1);
}
for(i = 0; i < parts.length; i += 1) {
if(typeof parent[parts[i]] === "undefined") {
parent[parts[i]] = {};
parent = parent[parts[i]];
}
return parent;
}
};
diem.defineNamespace('diem.utils');
// module pattern
diem.utils = (function() {
// private API
// ...
// public API
return {
handleFileInputs: function(container) {
$(container + ' ' + 'input[type="image"]').click(function(e) {
// prevent from submission
e.preventDefault();
// handle add/remove items
if($(this).hasClass('add')) {
$(this).parent().append('<p><input type="file" accept="image/jpeg,image/png,image/gif" name="files" /></p>');
} else {
$(this).parent().find('p:last-child').remove();
} // if($(this).hasClass('add')) {
});
}, // handleFileAttachments: function() {
handleLabelWidths: function(container) {
var max = 0;
$(container + ' ' + 'label.autoWidth').each(function() {
if($(this).width() > max) {
max = $(this).width();
}
});
$(container + ' ' + 'label.autoWidth').width(max + 5);
} // handleLabelWidths: function(container) {
} // return {
})(); // streamlined.utils = (function() {
Also there's a code that depends on Modernizr library.
How do I use my code, JQuery, Modernizr, and requirejs together?
Thanks!
Assuming you put all your .js files in a "scripts" subdirectory
<script data-main="scripts/main.js" src="scripts/require-jquery.js"></script>
In main.js
require(["jquery", "jquery.alpha", "jquery.beta"], function($) {
//the jquery.alpha.js and jquery.beta.js plugins have been loaded.
$(function() {
$('body').alpha().beta();
});
});

Problem with jquery.ui.autocomplete.js on IE7

Here is the code. IE7 spouts an "'active.0' is null or not an object" error on line 39, which is:
input.trigger("activate.autocomplete", [$.data(active[0], "originalObject")]); $("body").trigger("off.autocomplete");
Works perfectly in Firefox/Chrome/Opera. Any ideas? Many thanks and much appreciated.
/* jQuery Autocomplete
* Version 1.0
* Written by Yehuda Katz (wycats#gmail.com) and Rein Henrichs (reinh#reinh.com)
* #requires jQuery v1.2, jQuery dimensions plugin
*
* Copyright 2007 Yehuda Katz, Rein Henrichs
* Dual licensed under the MIT and GPL licenses:
* hxxp://www.opensource.org/licenses/mit-license.php
* hxxp://www.gnu.org/licenses/gpl.html
*
*/
/*
* #description Form autocomplete plugin using preloaded or Ajax JSON data source
*
* #example $('input#user-name').autocomplete({list: ["quentin", "adam", "admin"]})
* #desc Simple autocomplete with basic JSON data source
*
* #example $('input#user-name').autocomplete({ajax: "/usernames.js"})
* #desc Simple autocomplete with Ajax loaded JSON data source
*
*/
(function($) {
$.ui = $.ui || {}; $.ui.autocomplete = $.ui.autocomplete || {}; var active;
$.fn.autocompleteMode = function(container, input, size, opt) {
var original = input.val(); var selected = -1; var self = this;
$.data(document.body, "autocompleteMode", true);
$("body").one("cancel.autocomplete", function() {
input.trigger("cancel.autocomplete"); $("body").trigger("off.autocomplete"); input.val(original);
});
$("body").one("activate.autocomplete", function() {
input.trigger("activate.autocomplete", [$.data(active[0], "originalObject")]); $("body").trigger("off.autocomplete");
});
$("body").one("off.autocomplete", function(e, reset) {
container.remove();
$.data(document.body, "autocompleteMode", false);
input.unbind("keydown.autocomplete");
$("body").add(window).unbind("click.autocomplete").unbind("cancel.autocomplete").unbind("activate.autocomplete");
});
// If a click bubbles all the way up to the window, close the autocomplete
$(window).bind("click.autocomplete", function() { $("body").trigger("cancel.autocomplete"); });
var select = function() {
active = $("> *", container).removeClass("active").slice(selected, selected + 1).addClass("active");
input.trigger("itemSelected.autocomplete", [$.data(active[0], "originalObject")]);
input.val(opt.insertText($.data(active[0], "originalObject")));
};
container.mouseover(function(e) {
// If you hover over the container, but not its children, return
if(e.target == container[0]) return;
// Set the selected item to the item hovered over and make it active
selected = $("> *", container).index($(e.target).is('li') ? $(e.target)[0] : $(e.target).parents('li')[0]); select();
}).bind("click.autocomplete", function(e) {
$("body").trigger("activate.autocomplete"); $.data(document.body, "suppressKey", false);
});
input
.bind("keydown.autocomplete", function(e) {
if(e.which == 27) { $("body").trigger("cancel.autocomplete"); }
else if(e.which == 13) { $("body").trigger("activate.autocomplete"); }
else if(e.which == 40 || e.which == 9 || e.which == 38) {
switch(e.which) {
case 40:
case 9:
selected = selected >= size - 1 ? 0 : selected + 1; break;
case 38:
selected = selected <= 0 ? size - 1 : selected - 1; break;
default: break;
}
select();
} else { return true; }
$.data(document.body, "suppressKey", true);
});
};
$.fn.autocomplete = function(opt) {
opt = $.extend({}, {
timeout: 1000,
getList: function(input) { input.trigger("updateList", [opt.list]); },
template: function(str) { return "<li>" + opt.insertText(str) + "</li>"; },
insertText: function(str) { return str; },
match: function(typed) { return this.match(new RegExp(typed)); },
wrapper: "<ul class='jq-ui-autocomplete'></ul>"
}, opt);
if($.ui.autocomplete.ext) {
for(var ext in $.ui.autocomplete.ext) {
if(opt[ext]) {
opt = $.extend(opt, $.ui.autocomplete.ext[ext](opt));
delete opt[ext];
}
} }
return this.each(function() {
$(this)
.keypress(function(e) {
var typingTimeout = $.data(this, "typingTimeout");
if(typingTimeout) window.clearInterval(typingTimeout);
if($.data(document.body, "suppressKey"))
return $.data(document.body, "suppressKey", false);
else if($.data(document.body, "autocompleteMode") && e.charCode < 32 && e.keyCode != 8 && e.keyCode != 46) return false;
else {
$.data(this, "typingTimeout", window.setTimeout(function() {
$(e.target).trigger("autocomplete");
}, opt.timeout));
}
})
.bind("autocomplete", function() {
var self = $(this);
self.one("updateList", function(e, list) {
list = $(list)
.filter(function() { return opt.match.call(this.toLowerCase(), self.val()); })
.map(function() {
var node = $(opt.template(this))[0];
$.data(node, "originalObject", this);
return node;
});
$("body").trigger("off.autocomplete");
if(!list.length) return false;
var container = list.wrapAll(opt.wrapper).parents(":last").children();
var offset = self.offset();
opt.container = container
.css({top: offset.top + self.outerHeight(), left: offset.left, width: self.width()})
.appendTo("body");
$("body").autocompleteMode(container, self, list.length, opt);
});
opt.getList(self);
});
});
};
})(jQuery);
Check out:
http://github.com/istruble/jquery-autocomplete/commit/bdc926bd2c18c3ebab4e31463a8ae899fd761316#diff-1
It is a version of jquery.ui.autocomplete.js with most of the IE 7 issues fixed. I found a few more issues which I listed at the bottom along with how to fix them.
Here is my code that works javascript first:
$(".student_search").autocomplete("student_search.php", {
minChars: 2,
cacheLength: 20,
matchContains: true,
highlightItem: true,
parse: function(data) {
return $.map(eval(data), function(row) {
return {
data: row,
value: row.studentname, //value being searched for
result: row.studentidnumber //value in text input
}
});
},
formatItem: function(row, i, max, term) {
return "<span style='font-size: 110%;'>" + row.studentname + "</span><br/>" + "ID: " + row.studentidnumber + ", " + " Grade: " + row.studentgradenumber;
},
formatResult: function(row, i, max){
return row.studentidnumber;
}
});
});
Here is the code in the PHP file. It prints a JSON object with the data.
if(isset($_GET['q'])){
require_once("php/mysql.connect.php");
$request = strtolower($_GET['q']);
$query = mysql_query("SELECT
CONCAT(studentfname, ' ', studentlname, '')
AS studentname, studentidnumber,
CONCAT(studentgradenumber, 'th')
AS studentgradenumber
FROM studentinfo
WHERE studentlname LIKE '%".$request."%'
OR studentfname LIKE '%".$request."%'
OR studentidnumber LIKE '%".$request."%'") or die(mysql_error());
$results = array();
$i = 0;
while($row = mysql_fetch_assoc($query)) //fetch each result using the column name as the array key
{
foreach($row as $column=>$val) //loop through each column
{
$results[$i][$column] = $val; //build array using incremental row # and column name
}
$i++; //increase the row counter
}
print json_encode($results);
}
The JSON object that is printed is:
[{"studentname":"Joe Schmo","studentidnumber":"123456","studentgradenumber":"11th"}]
so row.studentname returns Joe Schmo. Where row is the name of the variable in the function and studentname is the name of the key from the JSON object.
Cheers!
I had problems with autocompletion of jquery ui version 1.8.9 and IE7. I use 1.8.16 now and it works.

Categories