Error: Cannot read property 'defaultView' of undefined, using jQuery - javascript

I have this code
$(document).ready(function (){
var Form_addTurbo = $('form#Form_addTurbo');
Form_addTurbo.submit(function (e){
e.preventDefault;
v = new Notification('Creating Turbo.', 'information', 'Working..', function(){return;});
$.post('/api/turbos/new.php', {
action : 'createNew'
}, function (r){
v.hide();
if(r.success){
new Notification('Turbo Create.', 'saved', '', function(){return;});
}else if(r.error){
}else{
new Notification('Something went wrong.', 'error', '', function(){return;});
}
}, 'json');
return false;
});
});
Which uses this api
$(document).ready(function(e) {$("body").prepend('<ul id="notifications"></ul>');});
/**
* Global notification system
*
* #param String Message to be displayed
* #param String Type of notification
*
* #author Bram Jetten
* #version 28-03-2011
*/
Notification.fn = Notification.prototype;
function Notification(value, type, tag, onclickfunc) {
this.log(value, type);
this.element = $('<li><span class="image '+ type +'"></span>' + value + '</li>');
if(typeof tag !== "undefined" && tag !== '') {
$(this.element).append('<span class="tag">' + tag + '</span>');
}
if(typeof onclickfunc == 'function'){
this.element.click(onclickfunc);
}
$("#notifications").append(this.element);
this.show();
}
/**
* Show notification
*/
Notification.fn.show = function() {
$(this.element).slideDown(200);
$(this.element).click(this.hide);
}
/**
* Hide notification
*/
Notification.fn.hide = function() {
$(this).animate({opacity: .01}, 200, function() {
$(this).slideUp(200, function() {
$(this).remove();
});
});
}
/**
* Log notification
*
* #param String Message to be logged
* #param String Type of notification
*/
Notification.fn.log = function(value, type) {
switch(type) {
case "information":
console.info("*** " + value + " ***");
break;
case "success":
console.log(value);
break;
case "warning":
console.warn(value);
break;
case "error":
console.error(value);
break;
case "saved":
console.log(value);
break;
default:
console.log(value);
break;
}
}
So what happens is that I try close the notification using the hide function that I believe it gives but I get this error.
Uncaught TypeError: Cannot read property 'defaultView' of undefined
I believe it doesn't know what "this" is but how would I be able to get this to work.

Made some minor changes to your example. Try it out http://jsfiddle.net/FLE39/
Had a closer look at your code and made a new jsfiddle. See updated link.

Related

jQuery.Popup is not a constructor & Query is not defined(anonymous function)

I've come to the tail end of a module I'm creating for Magento 2 but I'm having trouble getting it to render on the screen. This code has worked on other sites in the past but there seems to be an issue stopping this one from working. The issue seems to be with my code "var popup = new jQuery.Popup(poOptions);" note being recognized as a constructor.
I read through a few similar posts (like this one WOW is not a constructor) but I can't seem to figure out what the issue is still
The jquery plugin I'm utilizing originates from https://github.com/Toddish/Popup, on our website page here https://76a8q06e6vrsbggs.mojostratus.io/catalog/product/view/id/44/s/2018-official-joules-vest/category/5/
The idea is you add some custom text in the field labeled "personalize", click the preview button, and a window opens up showing the custom text you had on the item. The link the code constructs works fine, its the actual popup that renders the image that is the issue. I'm adding the code that seems relevant to the situation, hope someone can help me out here this has been a headscratcher especially since it works a lot of times, but if you refresh enough it breaks and I don't understand why.
Can anyone out there help me figure this out?
EDIT: I removed an additional jQuery Library call that seemed to be triggering some errors, having said that, it's still inconsistently working because sometimes I get the "(index):2025 Uncaught ReferenceError: jQuery is not defined" error.
<script type="text/javascript">
var liquifireArguments = [];
/*-------------------------------
POPUP.JS
Simple Popup plugin for jQuery
#author Todd Francis
#version 2.2.3
-------------------------------*/
;(function($, window){
'use strict';
/**
* Popup jQuery method
*
* #param {Object} settings
* #return {Object}
*/
$.fn.popup = function(settings){
var selector = this.selector,
popup = new $.Popup(settings);
$(document)
.on('click.popup', selector, function(e){
var content = settings && settings.content
? settings.content
: $(this).attr('href');
e.preventDefault();
popup.open(content, undefined, this);
});
return this.each(function(){
$(this)
.data('popup', popup);
});
};
/**
* Main Popup Class
*
* #param {Object} settings
*/
$.Popup = function(settings)
{
var p = this,
defaults = {
// Markup
backClass : 'popup_back',
backOpacity : 0.7,
containerClass : 'popup_cont',
closeContent : '<div class="popup_close">×</div>',
markup : '<div class="popup"><div class="popup_content"/></div>',
contentClass : 'popup_content',
preloaderContent : '<p class="preloader"> </p>',
activeClass : 'popup_active',
hideFlash : false,
speed : 200,
popupPlaceholderClass : 'popup_placeholder',
keepInlineChanges : true,
// Content
modal : false,
content : null,
type : 'auto',
width : null,
height : null,
// Params
typeParam : 'pt',
widthParam : 'pw',
heightParam : 'ph',
// Callbacks
beforeOpen : function(type){},
afterOpen : function(){},
beforeClose : function(){},
afterClose : function(){},
error : function(){},
show : function($popup, $back){
var plugin = this;
// Center the popup
plugin.center();
// Animate in
$popup
.animate({opacity : 1}, plugin.o.speed, function(){
// Call the open callback
plugin.o.afterOpen.call(plugin);
});
},
replaced : function($popup, $back){
// Center the popup and call the open callback
this
.center()
.o.afterOpen.call(this);
},
hide : function($popup, $back){
if( $popup !== undefined ){
// Fade the popup out
$popup.animate({opacity : 0}, this.o.speed);
}
},
types : {
inline : function(content, callback){
var $content = $(content);
$content
.addClass(p.o.popupPlaceholderClass);
// If we don't want to keep any inline changes,
// get a fresh copy now
if( !p.o.keepInlineChanges ){
cachedContent = $content.html();
}
callback.call(this, $content.children());
},
image : function(content, callback){
var plugin = this;
var mw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)-100;
var mh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)-100;
var $image = $('<img />')
.one('load', function(){
var img = this;
// Timeout for Webkit
// As the width/height of the image is 0 initially
setTimeout(function(){
callback.call(plugin, img);
}, 0);
})
.one('error', function(){
p.o.error.call(p, content, 'image');
})
.attr('src', content)
.css('max-width',mw)
.css('max-height',mh)
.each(function() {
if( this.complete ){
$(this).trigger('load');
}
});
},
external : function(content, callback){
var $frame = $('<iframe />')
.attr({
src : content,
frameborder : 0,
width : p.width,
height : p.height
});
callback.call(this, $frame);
},
html : function(content, callback){
callback.call(this, content);
},
jQuery : function(content, callback){
callback.call(this, content.html());
},
'function' : function(content, callback){
callback.call(this, content.call(p));
},
ajax : function(content, callback){
$.ajax({
url : content,
success : function(data){
callback.call(this, data);
},
error : function(data){
p.o.error.call(p, content, 'ajax');
}
});
}
}
},
imageTypes = ['png', 'jpg', 'gif'],
type,
cachedContent,
$back,
$pCont,
$close,
$preloader,
$p;
p.ele = undefined;
p.o = $.extend(true, {}, defaults, settings);
/**
* Opens a new popup window
*
* #param {string} content
* #param {string} popupType
* #param {Object} ele
* #return {void}
*/
p.open = function(content, popupType, ele){
// Get the content
content = ( content === undefined || content === '#' )
? p.o.content
: content;
// If no content is set
if( content === null ){
p.o.error.call(p, content, type);
return false;
}
// Was an element passed in?
if( ele !== undefined ){
// Remove current active class
if( p.ele && p.o.activeClass ){
$(p.ele).removeClass(p.o.activeClass);
}
// Record the element
p.ele = ele;
// Add an active class
if( p.ele && p.o.activeClass ){
$(p.ele).addClass(p.o.activeClass);
}
}
// If we're not open already
if( $back === undefined ){
// Create back and fade in
$back = $('<div class="'+p.o.backClass+'"/>')
.appendTo($('body'))
.css('opacity', 0)
.animate({
opacity : p.o.backOpacity
}, p.o.speed);
// If modal isn't specified, bind click event
if( !p.o.modal ){
$back.one('click.popup', function(){
p.close();
});
}
// Should we hide the flash?
if( p.o.hideFlash ){
$('object, embed').css('visibility', 'hidden');
}
// Preloader
if( p.o.preloaderContent ){
$preloader = $(p.o.preloaderContent)
.appendTo($('body'));
}
}
// Get the popupType
popupType = getValue([popupType, p.o.type]);
// If it's at auto, guess a real type
popupType = ( popupType === 'auto' )
? guessType(content)
: popupType;
// Cache the type to use globally
type = popupType;
// Do we have a width set?
p.width = ( p.o.width )
? p.o.width
: null;
// Do we have a height set?
p.height = ( p.o.height )
? p.o.height
: null;
// If it's not inline, jQuery or a function
// it might have params, and they are top priority
if( $.inArray(popupType, ['inline', 'jQuery', 'function']) === -1 ){
var paramType = getParameterByName(p.o.typeParam, content),
paramWidth = getParameterByName(p.o.widthParam, content),
paramHeight = getParameterByName(p.o.heightParam, content);
// Do we have an overriding paramter?
popupType = ( paramType !== null )
? paramType
: popupType;
// Do we have an overriding width?
p.width = ( paramWidth !== null )
? paramWidth
: p.width;
// Do we have an overriding height?
p.height = ( paramHeight !== null )
? paramHeight
: p.height;
}
// Callback
p.o.beforeOpen.call(p, popupType);
// Show the content based
if( p.o.types[popupType] ){
p.o.types[popupType].call(p, content, showContent);
}else{
p.o.types.ajax.call(p, content, showContent);
}
};
/**
* Return the correct value to be used
*
* #param {array} items
* #return {mixed}
*/
function getValue(items){
var finalValue;
$.each(items, function(i, value){
if( value ){
finalValue = value;
return false;
}
});
return finalValue;
}
/**
* Guess the type of content to show
*
* #param {string|Object|function} content
* #return {string}
*/
function guessType(content){
if( typeof content === 'function' ){
return 'function';
} else if( content instanceof $ ){
return 'jQuery';
} else if( content.substr(0, 1) === '#' || content.substr(0, 1) === '.' ){
return 'inline';
} else if( $.inArray(content.substr(content.length - 3), imageTypes) !== -1 ) {
return 'image';
} else if( content.substr(0, 4) === 'http' ) {
return 'external';
}else{
return 'ajax';
}
}
/**
* Shows the content
*
* #param {string} content
* #return {void}
*/
function showContent(content){
// Do we have a preloader?
if( $preloader ){
// If so, hide!
$preloader.fadeOut('fast', function(){
$(this).remove();
});
}
// Presume we're replacing
var replacing = true;
// If we're not open already
if( $pCont === undefined ){
// We're not replacing!
replacing = false;
// Create the container
$pCont = $('<div class="'+p.o.containerClass+'">');
// Add in the popup markup
$p = $(p.o.markup)
.appendTo($pCont);
// Add in the close button
$close = $(p.o.closeContent)
.one('click', function(){
p.close();
})
.appendTo($pCont);
// Bind the resize event
$(window).resize(p.center);
// Append the container to the body
// and set the opacity
$pCont
.appendTo($('body'))
.css('opacity', 0);
}
// Get the actual content element
var $pContent = $('.'+p.o.contentClass, $pCont);
// Do we have a set width/height?
if( p.width ){
$pContent.css('width', p.width, 10);
}else{
$pContent.css('width', '');
var mw = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)-100;
$pContent.css('max-width', mw);
}
if( p.height ){
$pContent.css('height', p.height, 10);
}else{
$pContent.css('height', '');
var mh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)-100;
$pContent.css('max-height', mh);
}
// Put the content in place!
if( $p.hasClass(p.o.contentClass) ){
$p
.html(content);
}else{
$p
.find('.'+p.o.contentClass)
.html(content);
}
// Callbacks!
if( !replacing ){
p.o.show.call(p, $pCont, $back);
}else{
p.o.replaced.call(p, $pCont, $back);
}
}
/**
* Close the popup
*
* #return {Object}
*/
p.close = function(){
p.o.beforeClose.call(p);
// If we got some inline content, cache it
// so we can put it back
if(
type === 'inline' &&
p.o.keepInlineChanges
){
cachedContent = $('.'+p.o.contentClass).html();
}
if( $back !== undefined ){
// Fade out the back
$back.animate({opacity : 0}, p.o.speed, function(){
// Clean up after ourselves
p.cleanUp();
});
}
// Call the hide callback
p.o.hide.call(p, $pCont, $back);
return p;
};
/**
* Clean up the popup
*
* #return {Object}
*/
p.cleanUp = function(){
$back
.add($pCont)
.remove();
$pCont = $back = undefined;
// Unbind the resize event
$(window).unbind('resize', p.center);
// Did we hide the flash?
if( p.o.hideFlash ){
$('object, embed').css('visibility', 'visible');
}
// Remove active class if we can
if( p.ele && p.o.activeClass ){
$(p.ele).removeClass(p.o.activeClass);
}
var $popupPlaceholder = $('.'+p.o.popupPlaceholderClass);
// If we got inline content
// put it back
if(
type == 'inline' &&
$popupPlaceholder.length
){
$popupPlaceholder
.html(cachedContent)
.removeClass(p.o.popupPlaceholderClass);
}
type = null;
// Call the afterClose callback
p.o.afterClose.call(p);
return p;
};
/**
* Centers the popup
*
* #return {Object}
*/
p.center = function(){
$pCont.css(p.getCenter());
// Only need force for IE6
$back.css({
height : document.documentElement.clientHeight
});
return p;
};
/**
* Get the center co-ordinates
*
* Returns the top/left co-ordinates to
* put the popup in the center
*
* #return {Object} top/left keys
*/
p.getCenter = function(){
var pW = $pCont.children().outerWidth(true),
pH = $pCont.children().outerHeight(true),
wW = document.documentElement.clientWidth,
wH = document.documentElement.clientHeight;
return {
top : wH * 0.5 - pH * 0.5,
left : wW * 0.5 - pW * 0.5
};
};
/**
* Get parameters by name
* #param {string} name
* #return {null|string} null if not found
*/
function getParameterByName(name, url){
var match = new RegExp('[?&]'+name+'=([^&]*)')
.exec(url);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
};
}(jQuery, window));
</script>
/*optionId = InputId Of Personalization field*/
var personalizedField = document.getElementsByClassName('product-custom-option')[0].id;
//!TODO: String/VAR TO ARRAY
// console.log('personalizedField: ' + personalizedField);
arguments = {optionId:personalizedField, argument:'<?= $liquifire_argument ?>'};
// console.log("arguments: " + arguments);
liquifireArguments.push(arguments);
jQuery( document ).ready(function(){
function lpiEncode(str) {
var encoded = str;
encoded = encoded.replace(/&/g, "U0026amp;");
encoded = encoded.replace(/'/g, "U0027");
encoded = encoded.replace(/\(/g, "U0026lp;");
encoded = encoded.replace(/\)/g, "U0026rp;");
encoded = encoded.replace(/\[/g, "U005B");
encoded = encoded.replace(/\]/g, "U005D");
encoded = encoded.replace(/\`/g, "U0060");
encoded = encoded.replace(/\+/g, "%2b");
return encoded;
}
jQuery('#product-options-wrapper').append('<div class="lp-box"><button type="button" title="Preview" class="button" id="liquifire-preview"><span><span>Preview</span></span></button></div>');
jQuery('#liquifire-preview').click(function(){
//jQuery('.mousetrap').addClass('liquidpixels');
var liquifireUrl = 'https://urm.liquifire.com/urm';
var liquifireChain = '<?= $image_chain ?>';
var imageUrl = liquifireUrl + '?';
// console.log("liquifireUrl: " + liquifireUrl);
// console.log("liquifireChain: " + liquifireChain);
// console.log("imageUrl: " + imageUrl);
jQuery.each(liquifireArguments, function(){
optionValue = document.getElementById(this.optionId).value;
if( optionValue !== ''){
var argument = this.argument;
if(liquifireArguments.indexOf(this) === 0){
imageUrl += 'set=';
}else{
imageUrl += ',';
}
// Add variable and value
imageUrl += argument + '[' + lpiEncode(optionValue) + ']';
}
});
if(document.getElementById('select_label_color')) {
lpcolor = document.getElementById('select_label_color').textContent.toLowerCase();
if( lpcolor !== ''){
imageUrl += ',selColor[' + lpcolor + '.jpg]';
}
}
// Zoom Url
zoomUrl = imageUrl + '&call=url[file:' + liquifireChain + ']&scale=size[1000]&sink';
// console.log('zoomUrl: '+ zoomUrl);
// Add image chain
imageUrl += '&call=url[file:' + liquifireChain + ']&scale=size[900]&sink';
// console.log('imageUrl: '+ imageUrl);
var poOptions = { type : 'image' };
var popup = new jQuery.Popup(poOptions);
popup.open(zoomUrl);
});
});
</script>
This seems to be a relatively common Magento 2 issue for custom modules. There are a number of solutions out there that may be better than this one, having said that, the one I found here https://www.offset101.com/magento-2-x-fix-uncaught-referenceerror-jquery-not-definedanonymous-function-javascript-message/ was the most straight forward.
Wrapping my code in the below require function did the trick.
require(['jquery'],function($){
$(document).ready(function(){
alert('YOUR JS HERE');
});
});

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.

Cannot read property 'offsetHeight' of null

I have strange issue showed up recently on my script and not sure what causes this issue to happen. It is popping up on Chrome browser mainly and I guess this function 'offsetHeight' is either deprecated or invalid.
here is the full code:
var Rep_Templates = {
// array of pre-defined reasons
answers: null,
// popup container
context_menu: null,
// popup copntiner height
menu_height: 0,
error_msg: null,
// ajax form and its param values
pseudoform: null,
url: null,
postid: 0,
// information phrases to display to user
thanks_phrase: '',
description_msg: '',
timer_id: null,
/**
* inits the popup
* #param answers array of pre-defined reasons
* #param error_msg to display in case of empty message
* #param url of current page
* #param thanks_phrase diaplyed after successful submission
*/
init: function(answers, url, phrases) {
if (AJAX_Compatible)
{
this.answers = answers;
this.error_msg = phrases['error'];
this.thanks_phrase = phrases['thanks'];
this.description_msg = phrases['description'];
this.context_menu = new YAHOO.widget.Menu("rep_tmpl_popup",
{clicktohide: false,
effect: {
effect: YAHOO.widget.ContainerEffect.FADE,
duration: 0.25
}});
// Fix for IE7 z-index bug
if (YAHOO.env.ua.ie && YAHOO.env.ua.ie < 8)
{
this.context_menu.cfg.setProperty("position", "dynamic");
this.context_menu.cfg.setProperty("iframe", true);
this.context_menu.cfg.setProperty("zindex", 10100);
}
this.context_menu.render(document.body);
var menu_object = fetch_object("rep_tmpl_menu_inner");
this.menu_height = menu_object.offsetHeight;
var links = YAHOO.util.Dom.getElementsByClassName("report", "a", document.body);
for ( var i = 0; i < links .length; i++ ) {
var index = links[i].href.indexOf("p=");
if (index > 0)
{
var postid = links[i].href.substr(index+2);
YAHOO.util.Event.on(links[i], "click", this.show_popup, postid);
}
}
this.pseudoform = new vB_Hidden_Form('ajax.php');
this.pseudoform.add_variable('ajax', 1);
this.pseudoform.add_variable('s', fetch_sessionhash());
this.pseudoform.add_variable('securitytoken', SECURITYTOKEN);
this.pseudoform.add_variable('do', 'email_report');
this.url = url;
}
},
/**
* inserts pre-defined reason into textarea
* #param id of selected reason
*/
set_answer: function(id) {
var textarea = fetch_object('rep_tmpl_message');
textarea.value = '';
if (id > 0 && id <= this.answers.length)
{
textarea.value = this.answers[id-1];
var error_msg = fetch_object('rep_tmpl_error');
error_msg.innerHTML = "";
}
},
/**
* show popup to the user
* #param event click event
* #param postid id of the post
*/
show_popup: function(event,postid) {
Rep_Templates.reset_data();
YAHOO.util.Event.stopEvent(event);
var elem = event.srcElement? event.srcElement : event.target;
Rep_Templates.postid = postid;
var xy = [0,0];
xy[0] = YAHOO.util.Dom.getX(elem) + 25;
xy[1] = YAHOO.util.Dom.getY(elem) - Rep_Templates.menu_height;
if (xy[1] < 0)
{
xy[1] = 0;
}
Rep_Templates.context_menu.moveTo(xy[0],xy[1]);
Rep_Templates.context_menu.show();
fetch_object('rep_tmpl_message').focus();
YAHOO.util.Event.on(document.body, "click", Rep_Templates.hide_menu);
},
/**
* hides the menu when users click Hide button or click outside of the popup. Resets data
* #param optional event. If specified, then user clicked outside.
*/
hide_menu: function(event) {
var is_inside = false;
if (event)
{
// check if click was inside or outside popup
var obj = event.srcElement? event.srcElement : event.target;
do {
if (obj.id == 'rep_tmpl_popup') {
is_inside = true;
break;
}
} while (obj = obj.parentNode);
if (!is_inside)
{
YAHOO.util.Event.removeListener(document.body, "click", Rep_Templates.hide_menu);
}
}
if (!event || !is_inside)
{
Rep_Templates.context_menu.hide();
Rep_Templates.postid = 0;
}
},
/**
* reset all fields with default values
*/
reset_data: function() {
var error_msg = fetch_object('rep_tmpl_error');
error_msg.innerHTML = "";
var phrase = fetch_object('rep_tmpl_phrase');
phrase.innerHTML = this.description_msg;
YAHOO.util.Dom.removeClass(phrase, 'rep_tmpl_thanks_message');
var button = fetch_object('rep_tmpl_submit');
YAHOO.util.Dom.removeClass(button, 'disabled');
button.disabled = false;
var image = fetch_object('rep_tmpl_progress');
image.style.display = 'none';
},
/**
* sends AJAX request
* #param event click event
*/
send_data: function(event) {
var textarea = fetch_object('rep_tmpl_message');
if (textarea && textarea.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') != '')
{
this.pseudoform.add_variable('postid', this.postid);
this.pseudoform.add_variable('url',this.url + "&p="+ this.postid + "#post" + this.postid);
var button = event.srcElement? event.srcElement : event.target;
button.disabled = true;
YAHOO.util.Dom.addClass(button, 'disabled');
var image = fetch_object('rep_tmpl_progress');
image.style.display = '';
YAHOO.util.Connect.asyncRequest("POST", 'ajax.php', {
success: this.handle_ajax_response,
failure: vBulletin_AJAX_Error_Handler,
timeout: vB_Default_Timeout,
scope: this
}, this.pseudoform.build_query_string() + '&reason=' + textarea.value);
}
else
{
var error_msg = fetch_object('rep_tmpl_error');
error_msg.innerHTML = this.error_msg;
}
return false;
},
/**
* handles AJAX request
* #param ajax data returned
*/
handle_ajax_response: function(ajax) {
if (ajax.responseXML)
{
// check for error first
var error = ajax.responseXML.getElementsByTagName('error');
if (error.length)
{
this.reset_data();
var error_msg = fetch_object('rep_tmpl_error');
error_msg.innerHTML = error[0].firstChild.nodeValue;
}
else
{
var result = ajax.responseXML.getElementsByTagName('result');
if (result.length)
{
var image = fetch_object('rep_tmpl_progress');
image.style.display = 'none';
var phrase = fetch_object('rep_tmpl_phrase');
phrase.innerHTML = this.thanks_phrase;
YAHOO.util.Dom.addClass(phrase, 'rep_tmpl_thanks_message');
this.timer_id = setTimeout('Rep_Templates.handle_timer_expiration()',1000);
}
}
}
},
/**
* hides popup on timer expiration
*/
handle_timer_expiration: function() {
clearTimeout(this.timer_id);
this.hide_menu();
}
}
any idea how to solve this issue!!
Thanks
Your problem is that the object menu_object is null. My guess is that the element that you are looking for does not exist. Check out your element and make sure that it has the correct identifier (class or id) to match fetch_object("rep_tmpl_menu_inner")

Jquery conflict between two versions

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>

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