JavaScript Resize Height Issue - javascript

Im stuck on a JavaScript Issue, which I have no idea how to resolve.
I have a Contact Modal within a Blog: http://www.northernvirginiapaintingcontractor.com/blog Click "Send a Page"
When you click on this you will see the issue. The Contact Modal doesn't open all of the way.
Compare that with the same "Send a Page" button on the Parent Application which functions normal. http://www.northernvirginiapaintingcontractor.com
This utilizes a modified version of Eric Martin's Simple Modal.
The Contact.js was modified to enable dynamic height, as well as, several different Contact Modals to be utilized with the same script.
3 other .js files include:
actual.js
jquery-easing-1.3.pack.js
jquery-easing-compatibility.1.2.pack.js
Here is the contact.js that has the problem: I don't have the slightest clue, if someone else does that would be great.
jQuery(function ($) {
var contact = {
message: null,
init: function () {
$('#contact-form input.contact, a.contact').click(function (e) {
e.preventDefault();
// Create the 1stModal dialog with the data
$('#modal-contact-form').modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>Close Pager Modal</a>",
//maxHeight: 62,
//maxWidth: 62,
//minHeight: 62,
//minWidth: 62,
position: [98, 377],
//autoPosition: false,
autoResize: true,
//overlayId: 'contact-overlay',
containerId: 'contact-container',
containerCss: { 'width': '350px'},
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
$('#contact-form input.suportecontacto, a.suportecontacto').click(function (e) {
e.preventDefault();
// Create the 2nd Modal dialog with the data
$('#modal-soporte-form').modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>Close Ticket Modal</a>",
//maxHeight: 62,
//maxWidth: 62,
//minHeight: 62,
//minWidth: 62,
position: [98, 377],
//autoPosition: false,
autoResize: true,
//overlayId: 'contact-overlay',
containerId: 'contact-container',
containerCss: { 'width': '350px' },
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
$('#contact-indivform input.indivcontacto, a.indivcontacto').click(function (e) {
e.preventDefault();
// Create the 3rd Modal dialog with the data
$('#modal-indivcontact-form').modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>Close Contacto Modal</a>",
//maxHeight: 62,
//maxWidth: 62,
//minHeight: 62,
//minWidth: 62,
position: [98, 377],
//autoPosition: false,
autoResize: true,
//overlayId: 'contact-overlay',
containerId: 'contact-container',
containerCss: { 'width': '350px' },
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
$('#HeadLogin').click(function (e) {
e.preventDefault();
// Create the Login modal
$('#login_form').modal({
closeHTML: "<a href='#' title='Cerrar' class='modal-close' style='padding-right:15px'>Cerrar Login Modal</a>",
//maxHeight: 62,
//maxWidth: 62,
//minHeight: 62,
//minWidth: 62,
position: [110, 364],
//autoPosition: false,
autoResize: true,
//overlayId: 'contact-overlay',
containerId: 'contact-container',
containerCss: { 'width': '310px' },
onOpen: contact.open,
onShow: contact.login,
onClose: contact.close
});
});
},
open: function (dialog) {
$('#ajax_loading').hide();
$('.simplemodal-wrap').css('overflow-x', 'visible').css('overflow-y', 'visible');
// add padding to the buttons in firefox/mozilla
if ($.browser.mozilla) {
$('#contact-container .contact-button').css({
'padding-bottom': '2px'
});
}
// input field font size
if ($.browser.safari) {
$('#contact-container .contact-input').css({
'font-size': '.9em'
});
}
// Dynamically determine Modal Height
//var h = 280;
//var h = 220;
//if ($('#contact-subject').length) {
// h += 26;
//}
//if ($('#contact-cc').length) {
// h += 22;
//}
var h = $('#contact-container form').actual('outerHeight') + 30;
var title = $('#contact-container .contact-title').html();
$('#contact-container .contact-title').html('Loading...');
dialog.overlay.fadeIn(200, function () {
dialog.container.fadeIn(200, function () {
dialog.data.fadeIn(200, function () {
$('#contact-container .contact-content').animate({
height: h
}, function () {
$('#contact-container .contact-title').html(title);
$('#contact-container form').fadeIn(200, function () {
$('#contact-container #contact-name').focus();
$('#contact-container .contact-cc').click(function () {
var cc = $('#contact-container #contact-cc');
cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
});
// fix png's for IE 6
if ($.browser.msie && $.browser.version < 7) {
$('#contact-container .contact-button').each(function () {
if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
var src = RegExp.$1;
$(this).css({
backgroundImage: 'none',
filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '", sizingMethod="crop")'
});
}
});
}
});
});
});
});
});
},
login: function() {
$('#contact-container .contact-send').click(function (e) {
e.preventDefault();
// Hide 'Submit' Button
if (contact.validateLogin()) {
$('.contact-send').hide();
$('.contact-cancel').hide();
// Show Gif Spinning Rotator
$('#ajax_loading').show();
// 'this' refers to the current submitted form
var url ='';
var str = $('#frmlogin').serialize();
var path = window.location.pathname;
var sub = 'Account';
if(path.toUpperCase().indexOf(sub.toUpperCase()) != -1) {
url = 'Login.aspx';
var image = $('#ajax_loading img');
image.attr('src','../images/spinner.gif');
}
else {
url = 'Account/Login.aspx';
}
// -- Start AJAX Call --
var form = $('#status form');
$.ajax({
type: "POST",
//url: form[0].action,
url: url,
data: str,
success: function (msg) {
$("#status").ajaxComplete(function (event, request, settings) {
// Show 'Submit' Button
$('.contact-send').show();
$('.contact-cancel').show();
// Hide Gif Spinning Rotator
$('#ajax_loading').hide();
if (msg != 'False') // LOGIN OK?
{
var login_response = '<div style="color:green; margin: 1px; float: right; width: 300px;">Ya Estás Conectado!<br />Por favor, espera mientras estas redirigido...</div>';
$('.contact-title').hide();
$('a.modalCloseImg').hide();
$('#frmlogin').hide();
$('#simplemodal-container').css("width", "500px");
$('#simplemodal-container').css("height", "140px");
$('#login_form .contact-message').html(login_response).show(); // Refers to 'status'
// After 1 second redirect the Logged-in User
setTimeout(contact.redirect, 500);
}
else // ERROR?
{
$('#login_form .contact-content').css("height", "150px");
$('#login_form .contact-message').html("Login failed!").css('color','red').show();
}
});
}
});
}
// -- End AJAX Call --
else {
if ($('#login_form .contact-message:visible').length > 0) {
var msg = $('#login_form .contact-message div');
msg.fadeOut(200, function () {
msg.empty();
contact.showError();
msg.fadeIn(200);
});
}
else {
$('#login_form .contact-message').animate({
height: '30px'
}, contact.showError);
}
}
});
},
redirect: function() {
window.location = '/'; // Members Area
},
show: function (dialog) {
$('#contact-container .contact-send').click(function (e) {
e.preventDefault();
var form = $('#contact-container form');
// validate form
if (contact.validate()) {
var msg = $('#contact-container .contact-message');
msg.fadeOut(function () {
msg.removeClass('contact-error').empty();
});
$('#contact-container .contact-title').html('Sending...');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: '80px'
}, function () {
var uname = $('#contact-container #contact-name').val();
var email = $('#contact-container #contact-email').val();
var cntx = $('#contact-container #contact-message').val();
var docc = "false";
if ($('#contact-container #contact-cc').is(':checked')) {
docc = "true";
}
$.ajax({
url: "blog/api/Blogs.asmx/SendMail",
data: "{'uname':'" + uname + "', 'email':'" + email + "','cntx':'" + cntx + "','docc':'" + docc + "'}",
type: "POST",
contentType: "application/json",
success: function (msg) {
//contact.close(dialog);
$('#contact-container .contact-loading').fadeOut(200, function () {
$('#contact-container .contact-title').html('Thank you!');
msg.html(data).fadeIn(200);
setTimeout(function () {
contact.close(dialog);
}, 1500);
});
}
});
contact.close(dialog);
});
}
else {
if ($('#contact-container .contact-message:visible').length > 0) {
var msg = $('#contact-container .contact-message div');
msg.fadeOut(200, function () {
msg.empty();
contact.showError();
msg.fadeIn(200);
});
}
else {
$('#contact-container .contact-message').animate({
height: '30px'
}, contact.showError);
}
}
});
},
close: function (dialog) {
$('#contact-container .contact-message').fadeOut();
$('#contact-container .contact-title').html('Closing...');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: 40
}, function () {
dialog.data.fadeOut(200, function () {
dialog.container.fadeOut(200, function () {
dialog.overlay.fadeOut(200, function () {
$.modal.close();
});
});
});
});
},
error: function (xhr) {
alert(xhr.statusText);
},
validateLogin: function () {
contact.message = '';
if (!$('#username').val()) {
contact.message += 'User name is required. ';
}
var pass = $('#password').val();
if (!pass) {
contact.message += 'Password is required. ';
}
if (contact.message.length > 0) {
return false;
}
else {
return true;
}
},
validate: function () {
contact.message = '';
if (!$('#contact-container input[name="name"]').val()) {
contact.message += 'Name is required. ';
}
var email = $('#contact-container input[name="email"]').val();
if (!email) {
contact.message += 'Email is required. ';
}
else {
if (!contact.validateEmail(email)) {
contact.message += 'Email is invalid. ';
}
}
if (!$('#contact-container textarea[name="message"]').val()) {
contact.message += 'Message is required.';
}
if (contact.message.length > 0) {
return false;
}
else {
return true;
}
},
validateEmail: function (email) {
var at = email.lastIndexOf("#");
// Make sure the at (#) sybmol exists and
// it is not the first or last character
if (at < 1 || (at + 1) === email.length)
return false;
// Make sure there aren't multiple periods together
if (/(\.{2,})/.test(email))
return false;
// Break up the local and domain portions
var local = email.substring(0, at);
var domain = email.substring(at + 1);
// Check lengths
if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
return false;
// Make sure local and domain don't start with or end with a period
if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
return false;
// Check for quoted-string addresses
// Since almost anything is allowed in a quoted-string address,
// we're just going to let them go through
if (!/^"(.+)"$/.test(local)) {
// It's a dot-string address...check for valid characters
if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
return false;
}
// Make sure domain contains only valid characters and at least one period
if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
return false;
return true;
},
showError: function () {
$('#contact-container .contact-message')
.html($('<div class="contact-error"></div>').append(contact.message))
.fadeIn(200);
}
};
contact.init();
});

This:
$('.contact-send').hide();
$('.contact-cancel').hide();
add's display:none; to those elements and they aren't removed when you call "open"

The simpleModal plugin programatically assigns the .simplemodal-wrap class
with a height of 100%, but the jquery.actual plugin fails to find the correct
height of the modal form during page resize because of this.
As a work-around I re-set the min-height to a value that displays the full
form no matter what.
.simplemodal-wrap {
min-height: 350px;
height: auto !important; /* needed for IE6 and below /
height: 350px; / needed for IE6 and below */
}
site.cshtml:
The element at line 129:
had a inline style == "display: none; ". This was not being changed to display: block; when the contact modal was opened. I chose to remove the inline style because one of the ancestor elements already has display: none; specified and when the modal opened that was being changed correctly.

Related

How can I make my JQuery run again when using goBack() in React

I have react app using Switch of react-router-dom. When people click they can see the profile of a person in full, but I want a goBack button, so I did this.
const onClick = () => {
return history.goBack();
}
The problem is, when I go back to the last page, the jQuery libraries I'm using don't work, and even some code I'm using in useEffect. I'm using forceRefresh in my Router so every time I go to another page in the Switch I can see the animations an load the actions, is not the best solution but has been working so far.
EDIT:
I'm adding the jQuery file, maybe this helps. This file is called in index.html of the public folder
<script src="%PUBLIC_URL%/assets/js/custom.js" async defer></script>
Code:
(function ($) {
'use strict';
$(document).ready(function () {
$(function () {
function mmenuInit() {
var wi = $(window).width();
if (wi <= '1099') {
$('.mmenu-init').remove();
$('#navigation')
.clone()
.addClass('mmenu-init')
.insertBefore('#navigation')
.removeAttr('id')
.removeClass('style-1 style-2')
.find('ul, div')
.removeClass(
'style-1 style-2 mega-menu mega-menu-content mega-menu-section'
)
.removeAttr('id');
$('.mmenu-init').find('ul').addClass('mm-listview');
$('.mmenu-init').find('.mobile-styles .mm-listview').unwrap();
$('.mmenu-init').mmenu(
{
counters: true,
},
{
// configuration
offCanvas: {
pageNodetype: '#wrapper',
},
}
);
var mmenuAPI = $('.mmenu-init').data('mmenu');
var $icon = $('.mmenu-trigger .hamburger');
$(document).on('click', '.mmenu-trigger', function () {
mmenuAPI.open();
});
}
$('.mm-next').addClass('mm-fullsubopen');
}
mmenuInit();
$(window).resize(function () {
mmenuInit();
});
});
$(window).on('load resize', function () {
var transparentHeaderHeight = $('.transparent-header').outerHeight();
$('.transparent-header-spacer').css({
height: transparentHeaderHeight,
});
});
$('.ripple-effect, .ripple-effect-dark').on('click', function (e) {
var rippleDiv = $('<span class="ripple-overlay">'),
rippleOffset = $(this).offset(),
rippleY = e.pageY - rippleOffset.top,
rippleX = e.pageX - rippleOffset.left;
rippleDiv
.css({
top: rippleY - rippleDiv.height() / 2,
left: rippleX - rippleDiv.width() / 2,
// background: $(this).data("ripple-color");
})
.appendTo($(this));
window.setTimeout(function () {
rippleDiv.remove();
}, 800);
});
$('.switch, .radio').each(function () {
var intElem = $(this);
intElem.on('click', function () {
intElem.addClass('interactive-effect');
setTimeout(function () {
intElem.removeClass('interactive-effect');
}, 400);
});
});
$(window).on('load', function () {
$('.button.button-sliding-icon')
.not('.task-listing .button.button-sliding-icon')
.each(function () {
var buttonWidth = $(this).outerWidth() + 30;
$(this).css('width', buttonWidth);
});
});
$('.bookmark-icon').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('bookmarked');
});
$('.bookmark-button').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('bookmarked');
});
$('a.close')
.removeAttr('href')
.on('click', function () {
function slideFade(elem) {
var fadeOut = { opacity: 0, transition: 'opacity 0.5s' };
elem.css(fadeOut).slideUp();
}
slideFade($(this).parent());
});
// Closing function
function close_user_dropdown() {
$('.header-notifications').removeClass('active');
}
// Closes notification dropdown on click outside the conatainer
var mouse_is_inside = false;
$('.header-notifications').on('mouseenter', function () {
mouse_is_inside = true;
});
$('.header-notifications').on('mouseleave', function () {
mouse_is_inside = false;
});
$('body').mouseup(function () {
if (!mouse_is_inside) close_user_dropdown();
});
// Close with ESC
$(document).keyup(function (e) {
if (e.keyCode == 27) {
close_user_dropdown();
}
});
if ($('.status-switch label.user-invisible').hasClass('current-status')) {
$('.status-indicator').addClass('right');
}
$('.status-switch label.user-invisible').on('click', function () {
$('.status-indicator').addClass('right');
$('.status-switch label').removeClass('current-status');
$('.user-invisible').addClass('current-status');
});
$('.status-switch label.user-online').on('click', function () {
$('.status-indicator').removeClass('right');
$('.status-switch label').removeClass('current-status');
$('.user-online').addClass('current-status');
});
// Wrapper Height (window height - header height)
function wrapperHeight() {
var headerHeight = $('#header-container').outerHeight();
var windowHeight = $(window).outerHeight() - headerHeight;
$(
'.full-page-content-container, .dashboard-content-container, .dashboard-sidebar-inner, .dashboard-container, .full-page-container'
).css({ height: windowHeight });
$('.dashboard-content-inner').css({ 'min-height': windowHeight });
}
// Enabling Scrollbar
function fullPageScrollbar() {
$('.full-page-sidebar-inner, .dashboard-sidebar-inner').each(function () {
var headerHeight = $('#header-container').outerHeight();
var windowHeight = $(window).outerHeight() - headerHeight;
var sidebarContainerHeight = $(this)
.find('.sidebar-container, .dashboard-nav-container')
.outerHeight();
// Enables scrollbar if sidebar is higher than wrapper
if (sidebarContainerHeight > windowHeight) {
$(this).css({ height: windowHeight });
} else {
$(this).find('.simplebar-track').hide();
}
});
}
// Init
$(window).on('load resize', function () {
wrapperHeight();
fullPageScrollbar();
});
wrapperHeight();
fullPageScrollbar();
// Sliding Sidebar
$('.enable-filters-button').on('click', function () {
$('.full-page-sidebar').toggleClass('enabled-sidebar');
$(this).toggleClass('active');
$('.filter-button-tooltip').removeClass('tooltip-visible');
});
/* Enable Filters Button Tooltip */
$(window).on('load', function () {
$('.filter-button-tooltip')
.css({
left: $('.enable-filters-button').outerWidth() + 48,
})
.addClass('tooltip-visible');
});
// Avatar Switcher
function avatarSwitcher() {
var readURL = function (input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.profile-pic').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
};
$('.file-upload').on('change', function () {
readURL(this);
});
$('.upload-button').on('click', function () {
$('.file-upload').click();
});
}
avatarSwitcher();
// Dashboard Nav Submenus
$('.dashboard-nav ul li a').on('click', function (e) {
if ($(this).closest('li').children('ul').length) {
if ($(this).closest('li').is('.active-submenu')) {
$('.dashboard-nav ul li').removeClass('active-submenu');
} else {
$('.dashboard-nav ul li').removeClass('active-submenu');
$(this).parent('li').addClass('active-submenu');
}
e.preventDefault();
}
});
// Responsive Dashbaord Nav Trigger
$('.dashboard-responsive-nav-trigger').on('click', function (e) {
e.preventDefault();
$(this).toggleClass('active');
var dashboardNavContainer = $('body').find('.dashboard-nav');
if ($(this).hasClass('active')) {
$(dashboardNavContainer).addClass('active');
} else {
$(dashboardNavContainer).removeClass('active');
}
$('.dashboard-responsive-nav-trigger .hamburger').toggleClass(
'is-active'
);
});
// Fun Facts
function funFacts() {
/*jslint bitwise: true */
function hexToRgbA(hex) {
var c;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length == 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
return (
'rgba(' +
[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',') +
',0.07)'
);
}
}
$('.fun-fact').each(function () {
var factColor = $(this).attr('data-fun-fact-color');
if (factColor !== undefined) {
$(this)
.find('.fun-fact-icon')
.css('background-color', hexToRgbA(factColor));
$(this).find('i').css('color', factColor);
}
});
}
funFacts();
// Notes & Messages Scrollbar
$(window).on('load resize', function () {
var winwidth = $(window).width();
if (winwidth > 1199) {
// Notes
$('.row').each(function () {
var mbh = $(this).find('.main-box-in-row').outerHeight();
var cbh = $(this).find('.child-box-in-row').outerHeight();
if (mbh < cbh) {
var headerBoxHeight = $(this)
.find('.child-box-in-row .headline')
.outerHeight();
var mainBoxHeight =
$(this).find('.main-box-in-row').outerHeight() -
headerBoxHeight +
39;
$(this)
.find('.child-box-in-row .content')
.wrap(
'<div class="dashboard-box-scrollbar" style="max-height: ' +
mainBoxHeight +
'px" data-simplebar></div>'
);
}
});
// Messages Sidebar
// var messagesList = $(".messages-inbox").outerHeight();
// var messageWrap = $(".message-content").outerHeight();
// if ( messagesList > messagesWrap) {
// $(messagesList).css({
// 'max-height': messageWrap,
// });
// }
}
});
// Mobile Adjustment for Single Button Icon in Dashboard Box
$('.buttons-to-right').each(function () {
var btr = $(this).width();
if (btr < 36) {
$(this).addClass('single-right-button');
}
});
// Small Footer Adjustment
$(window).on('load resize', function () {
var smallFooterHeight = $('.small-footer').outerHeight();
$('.dashboard-footer-spacer').css({
'padding-top': smallFooterHeight + 45,
});
});
// Auto Resizing Message Input Field
/* global jQuery */
jQuery.each(jQuery('textarea[data-autoresize]'), function () {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function (el) {
jQuery(el)
.css('height', 'auto')
.css('height', el.scrollHeight + offset);
};
jQuery(this)
.on('keyup input', function () {
resizeTextarea(this);
})
.removeAttr('data-autoresize');
});
function userMenuScrollbar() {
$('.header-notifications-scroll').each(function () {
var scrollContainerList = $(this).find('ul');
var itemsCount = scrollContainerList.children('li').length;
var notificationItems;
// Determines how many items are displayed based on items height
/* jshint shadow:true */
if (scrollContainerList.children('li').outerHeight() > 140) {
var notificationItems = 2;
} else {
var notificationItems = 3;
}
// Enables scrollbar if more than 2 items
if (itemsCount > notificationItems) {
var listHeight = 0;
$(scrollContainerList)
.find('li:lt(' + notificationItems + ')')
.each(function () {
listHeight += $(this).height();
});
$(this).css({ height: listHeight });
} else {
$(this).css({ height: 'auto' });
$(this).find('.simplebar-track').hide();
}
});
}
// Init
userMenuScrollbar();
/* global tippy */
tippy('[data-tippy-placement]', {
delay: 100,
arrow: true,
arrowType: 'sharp',
size: 'regular',
duration: 200,
// 'shift-toward', 'fade', 'scale', 'perspective'
animation: 'shift-away',
animateFill: true,
theme: 'dark',
// How far the tooltip is from its reference element in pixels
distance: 10,
});
var accordion = (function () {
var $accordion = $('.js-accordion');
var $accordion_header = $accordion.find('.js-accordion-header');
// default settings
var settings = {
// animation speed
speed: 400,
// close all other accordion items if true
oneOpen: false,
};
return {
// pass configurable object literal
init: function ($settings) {
$accordion_header.on('click', function () {
accordion.toggle($(this));
});
$.extend(settings, $settings);
// ensure only one accordion is active if oneOpen is true
if (settings.oneOpen && $('.js-accordion-item.active').length > 1) {
$('.js-accordion-item.active:not(:first)').removeClass('active');
}
// reveal the active accordion bodies
$('.js-accordion-item.active').find('> .js-accordion-body').show();
},
toggle: function ($this) {
if (
settings.oneOpen &&
$this[0] !=
$this
.closest('.js-accordion')
.find('> .js-accordion-item.active > .js-accordion-header')[0]
) {
$this
.closest('.js-accordion')
.find('> .js-accordion-item')
.removeClass('active')
.find('.js-accordion-body')
.slideUp();
}
// show/hide the clicked accordion item
$this.closest('.js-accordion-item').toggleClass('active');
$this.next().stop().slideToggle(settings.speed);
},
};
})();
$(document).ready(function () {
accordion.init({ speed: 300, oneOpen: true });
});
$(window).on('load resize', function () {
if ($('.tabs')[0]) {
$('.tabs').each(function () {
var thisTab = $(this);
// Intial Border Position
var activePos = thisTab.find('.tabs-header .active').position();
function changePos() {
// Update Position
activePos = thisTab.find('.tabs-header .active').position();
// Change Position & Width
thisTab
.find('.tab-hover')
.stop()
.css({
left: activePos.left,
width: thisTab.find('.tabs-header .active').width(),
});
}
changePos();
// Intial Tab Height
var tabHeight = thisTab.find('.tab.active').outerHeight();
// Animate Tab Height
function animateTabHeight() {
// Update Tab Height
tabHeight = thisTab.find('.tab.active').outerHeight();
// Animate Height
thisTab
.find('.tabs-content')
.stop()
.css({
height: tabHeight + 'px',
});
}
animateTabHeight();
// Change Tab
function changeTab() {
var getTabId = thisTab
.find('.tabs-header .active a')
.attr('data-tab-id');
// Remove Active State
thisTab
.find('.tab')
.stop()
.fadeOut(300, function () {
// Remove Class
$(this).removeClass('active');
})
.hide();
thisTab
.find('.tab[data-tab-id=' + getTabId + ']')
.stop()
.fadeIn(300, function () {
// Add Class
$(this).addClass('active');
// Animate Height
animateTabHeight();
});
}
// Tabs
thisTab.find('.tabs-header a').on('click', function (e) {
e.preventDefault();
// Tab Id
var tabId = $(this).attr('data-tab-id');
// Remove Active State
thisTab
.find('.tabs-header a')
.stop()
.parent()
.removeClass('active');
// Add Active State
$(this).stop().parent().addClass('active');
changePos();
// Update Current Itm
tabCurrentItem = tabItems.filter('.active');
// Remove Active State
thisTab
.find('.tab')
.stop()
.fadeOut(300, function () {
// Remove Class
$(this).removeClass('active');
})
.hide();
// Add Active State
thisTab
.find('.tab[data-tab-id="' + tabId + '"]')
.stop()
.fadeIn(300, function () {
// Add Class
$(this).addClass('active');
// Animate Height
animateTabHeight();
});
});
// Tab Items
var tabItems = thisTab.find('.tabs-header ul li');
// Tab Current Item
var tabCurrentItem = tabItems.filter('.active');
// Next Button
thisTab.find('.tab-next').on('click', function (e) {
e.preventDefault();
var nextItem = tabCurrentItem.next();
tabCurrentItem.removeClass('active');
if (nextItem.length) {
tabCurrentItem = nextItem.addClass('active');
} else {
tabCurrentItem = tabItems.first().addClass('active');
}
changePos();
changeTab();
});
// Prev Button
thisTab.find('.tab-prev').on('click', function (e) {
e.preventDefault();
var prevItem = tabCurrentItem.prev();
tabCurrentItem.removeClass('active');
if (prevItem.length) {
tabCurrentItem = prevItem.addClass('active');
} else {
tabCurrentItem = tabItems.last().addClass('active');
}
changePos();
changeTab();
});
});
}
});
// Thousand Separator
function ThousandSeparator(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
// Bidding Slider Average Value
var avgValue =
(parseInt($('.bidding-slider').attr('data-slider-min')) +
parseInt($('.bidding-slider').attr('data-slider-max'))) /
2;
if ($('.bidding-slider').data('slider-value') === 'auto') {
$('.bidding-slider').attr({ 'data-slider-value': avgValue });
}
// Bidding Slider Init
$('.bidding-slider').slider();
$('.bidding-slider').on('slide', function (slideEvt) {
$('#biddingVal').text(ThousandSeparator(parseInt(slideEvt.value)));
});
$('#biddingVal').text(
ThousandSeparator(parseInt($('.bidding-slider').val()))
);
// Default Bootstrap Range Slider
var currencyAttr = $('.range-slider').attr('data-slider-currency');
$('.range-slider').slider({
formatter: function (value) {
return (
currencyAttr +
ThousandSeparator(parseInt(value[0])) +
' - ' +
currencyAttr +
ThousandSeparator(parseInt(value[1]))
);
},
});
$('.range-slider-single').slider();
var radios = document.querySelectorAll('.payment-tab-trigger > input');
for (var i = 0; i < radios.length; i++) {
radios[i].addEventListener('change', expandAccordion);
}
function expandAccordion(event) {
/* jshint validthis: true */
var tabber = this.closest('.payment');
var allTabs = tabber.querySelectorAll('.payment-tab');
for (var i = 0; i < allTabs.length; i++) {
allTabs[i].classList.remove('payment-tab-active');
}
event.target.parentNode.parentNode.classList.add('payment-tab-active');
}
$('.billing-cycle-radios').on('click', function () {
if ($('.billed-yearly-radio input').is(':checked')) {
$('.pricing-plans-container').addClass('billed-yearly');
}
if ($('.billed-monthly-radio input').is(':checked')) {
$('.pricing-plans-container').removeClass('billed-yearly');
}
});
function qtySum() {
var arr = document.getElementsByName('qtyInput');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value)) tot += parseInt(arr[i].value);
}
}
qtySum();
$('.qtyDec, .qtyInc').on('click', function () {
var $button = $(this);
var oldValue = $button.parent().find('input').val();
if ($button.hasClass('qtyInc')) {
$button
.parent()
.find('input')
.val(parseFloat(oldValue) + 1);
} else {
if (oldValue > 1) {
$button
.parent()
.find('input')
.val(parseFloat(oldValue) - 1);
} else {
$button.parent().find('input').val(1);
}
}
qtySum();
$('.qtyTotal').addClass('rotate-x');
});
/* global ClipboardJS */
$('.copy-url input').val(window.location.href);
new ClipboardJS('.copy-url-button');
$('.share-buttons-icons a').each(function () {
var buttonBG = $(this).attr('data-button-color');
if (buttonBG !== undefined) {
$(this).css('background-color', buttonBG);
}
});
var $tabsNav = $('.popup-tabs-nav'),
$tabsNavLis = $tabsNav.children('li');
$tabsNav.each(function () {
var $this = $(this);
$this
.next()
.children('.popup-tab-content')
.stop(true, true)
.hide()
.first()
.show();
$this.children('li').first().addClass('active').stop(true, true).show();
});
$tabsNavLis.on('click', function (e) {
var $this = $(this);
$this.siblings().removeClass('active').end().addClass('active');
$this
.parent()
.next()
.children('.popup-tab-content')
.stop(true, true)
.hide()
.siblings($this.find('a').attr('href'))
.fadeIn();
e.preventDefault();
});
var hash = window.location.hash;
var anchor = $('.tabs-nav a[href="' + hash + '"]');
if (anchor.length === 0) {
$('.popup-tabs-nav li:first').addClass('active').show(); //Activate first tab
$('.popup-tab-content:first').show(); //Show first tab content
} else {
anchor.parent('li').click();
}
// Link to Register Tab
$('.register-tab').on('click', function (event) {
event.preventDefault();
$('.popup-tab-content').hide();
$('#register.popup-tab-content').show();
$('body')
.find('.popup-tabs-nav a[href="#register"]')
.parent('li')
.click();
});
// Disable tabs if there's only one tab
$('.popup-tabs-nav').each(function () {
var listCount = $(this).find('li').length;
if (listCount < 2) {
$(this).css({
'pointer-events': 'none',
});
}
});
$('.indicator-bar').each(function () {
var indicatorLenght = $(this).attr('data-indicator-percentage');
$(this)
.find('span')
.css({
width: indicatorLenght + '%',
});
});
var uploadButton = {
$button: $('.uploadButton-input'),
$nameField: $('.uploadButton-file-name'),
};
uploadButton.$button.on('change', function () {
_populateFileField($(this));
});
function _populateFileField($button) {
var selectedFile = [];
for (var i = 0; i < $button.get(0).files.length; ++i) {
selectedFile.push($button.get(0).files[i].name + '<br>');
}
uploadButton.$nameField.html(selectedFile);
}
$('.default-slick-carousel').slick({
infinite: false,
slidesToShow: 3,
slidesToScroll: 1,
dots: false,
arrows: true,
adaptiveHeight: true,
responsive: [
{
breakpoint: 1292,
settings: {
dots: true,
arrows: false,
},
},
{
breakpoint: 993,
settings: {
slidesToShow: 2,
slidesToScroll: 2,
dots: true,
arrows: false,
},
},
{
breakpoint: 769,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
dots: true,
arrows: false,
},
},
],
});
$('.testimonial-carousel').slick({
centerMode: true,
centerPadding: '30%',
slidesToShow: 1,
dots: false,
arrows: true,
adaptiveHeight: true,
responsive: [
{
breakpoint: 1600,
settings: {
centerPadding: '21%',
slidesToShow: 1,
},
},
{
breakpoint: 993,
settings: {
centerPadding: '15%',
slidesToShow: 1,
},
},
{
breakpoint: 769,
settings: {
centerPadding: '5%',
dots: true,
arrows: false,
},
},
],
});
$('.logo-carousel').slick({
infinite: true,
slidesToShow: 5,
slidesToScroll: 1,
dots: false,
arrows: true,
responsive: [
{
breakpoint: 1365,
settings: {
slidesToShow: 5,
dots: true,
arrows: false,
},
},
{
breakpoint: 992,
settings: {
slidesToShow: 3,
dots: true,
arrows: false,
},
},
{
breakpoint: 768,
settings: {
slidesToShow: 1,
dots: true,
arrows: false,
},
},
],
});
$('.mfp-gallery-container').each(function () {
// the containers for all your galleries
$(this).magnificPopup({
type: 'image',
delegate: 'a.mfp-gallery',
fixedContentPos: true,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: false,
preloader: true,
removalDelay: 0,
mainClass: 'mfp-fade',
gallery: { enabled: true, tCounter: '' },
});
});
$('.popup-with-zoom-anim').magnificPopup({
type: 'inline',
fixedContentPos: false,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
preloader: false,
midClick: true,
removalDelay: 300,
mainClass: 'my-mfp-zoom-in',
});
$('.mfp-image').magnificPopup({
type: 'image',
closeOnContentClick: true,
mainClass: 'mfp-fade',
image: {
verticalFit: true,
},
});
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false,
});
});
})(this.jQuery);
Thanks for any help.

Ajax Call with tab open

I have the following problem with jquery:
$(function() {
var linkCorretto = $("#id").text();
var authWindow;
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#' + modalLocation).reveal($(this).data());
});
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop',
animationspeed: 300,
closeonbackgroundclick: false,
dismissmodalclass: 'close'
};
var options = $.extend({}, defaults, options);
var altezza = $(window).height();
altezza = altezza * 0.5;
return this.each(function() {
var modal = $(this),
modalheight = modal.height() * 0.8;
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
if (modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
modal.bind('reveal:open', function() {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if (!locked) {
lockModal();
//modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(window).scrollTop()+topMeasure});
modal.css({
'opacity': 0,
'visibility': 'visible',
'top': $(window).scrollTop() + altezza - modalheight
});
$('body').css('overflow-y', 'hidden')
modalBG.fadeIn(options.animationspeed / 2);
modal.delay(options.animationspeed / 2).animate({
"opacity": 1
}, options.animationspeed, unlockModal());
}
modal.unbind('reveal:open');
$('.warning').hide();
$('.loading').hide();
$('.loadingoff').show();
$('.reveal-modal').addClass('background');
});
modal.bind('reveal:close', function() {
if (!locked) {
lockModal();
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity": 0
}, options.animationspeed, function() {
modal.css({
'opacity': 1,
'visibility': 'hidden',
'top': topMeasure
});
$('body').css('overflow-y', 'auto')
unlockModal();
});
}
modal.unbind('reveal:close');
});
modal.trigger('reveal:open')
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function() {
modal.trigger('reveal:close')
});
/*
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); }
});
*/
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});
}
// $.fn.reveal
$(".accetta").click(function() {
var dati = new Object();
dati = $("#listaCarte").val();
var imageUrl = '';
var x = ($('.reveal-modal').height());
$('.loadingoff').hide();
$('.loading').css('height', x).show();
$('.reveal-modal').removeClass('background');
$('<input>').attr({
type: 'hidden',
id: 'linkDaSostituire',
name: 'linkDaSostituire',
value: linkCorretto,
});
setTimeout(function() {
$.ajax({
type: "POST",
url: "/portalppay/ScontiServlet",
data: {
"linkDaSostituire": linkCorretto,
"cartaSelezionata": dati
},
dataType: "html",
success: function(msg) {
//window.location = msg;
authWindow = window.open('about:blank');
authWindow.location.replace(msg);
//window.open(msg);
//var win=window.location(msg, '_blank');
//win.focus();
$('.reveal-modal').trigger('reveal:close');
},
error: function() {
$('.loadingoff').hide();
$('.loading').hide();
$('.warning').css('height', x - 40).show();
}
});
}, 400);
});
// .accetta
});
when I trigger the ajax call, with this block of code:
url: "/portalppay/ScontiServlet",
I get a url for an answer and I do see in the browser with the following code:
authWindow = window.open('about:blank');
authWindow.location.replace(msg);
the problem is that I can not render the link in a new tab, but always in a new pop-up!
someone can help me solve the problem?
Have you checked your browser settings?
It's the browser which choose how to open new windows.
In Firefox there is the Open new windows in a new tab instead option which tells the browser if it has to open new windows in a new tab or in a... new window.
Do note that this works only if you are calling window.open without the strWindowFeatures parameter, specifying it forces the browser (well, at least Firefox and Explorer, Chrome does not seem to have a similar option) to open the link in a new window.
For more informations: https://developer.mozilla.org/en-US/docs/Web/API/window.open

How to send current URL in JavaScript?

I have a contact form. JavaScript with Ajax calls another contact-form.php file. Is there any way to send, with this JavaScript function, the current URL to the PHP file?
I want to see from which page my clients have contacted with me.
In contact-form.php:
$message .= "\n\Url: http://" .$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
this is not working.
My contact.js:
jQuery(function ($) {
var contact = {
message: null,
init: function () {
$('#contact-form input.contact, #contact-form a.contact').click(function (e) {
e.preventDefault();
// load the contact form using ajax
$.get("data/contact.php", function(data){
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Iki' class='modal-close'>x</a>",
position: ["15%",],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
},
open: function (dialog) {
// add padding to the buttons in firefox/mozilla
if ($.browser.mozilla) {
$('#contact-container .contact-button').css({
'padding-bottom': '2px'
});
}
// input field font size
if ($.browser.safari) {
$('#contact-container .contact-input').css({
'font-size': '.9em'
});
}
// dynamically determine height
var h = 280;
if ($('#contact-subject').length) {
h += 26;
}
if ($('#contact-cc').length) {
h += 22;
}
var title = $('#contact-container .contact-title').html();
$('#contact-container .contact-title').html('Palaukite...');
dialog.overlay.fadeIn(200, function () {
dialog.container.fadeIn(200, function () {
dialog.data.fadeIn(200, function () {
$('#contact-container .contact-content').animate({
height: h
}, function () {
$('#contact-container .contact-title').html(title);
$('#contact-container form').fadeIn(200, function () {
$('#contact-container #contact-name').focus();
$('#contact-container .contact-cc').click(function () {
var cc = $('#contact-container #contact-cc');
cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
});
// fix png's for IE 6
if ($.browser.msie && $.browser.version < 7) {
$('#contact-container .contact-button').each(function () {
if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
var src = RegExp.$1;
$(this).css({
backgroundImage: 'none',
filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '", sizingMethod="crop")'
});
}
});
}
});
});
});
});
});
},
show: function (dialog) {
$('#contact-container .contact-send').click(function (e) {
e.preventDefault();
// validate form
if (contact.validate()) {
var msg = $('#contact-container .contact-message');
msg.fadeOut(function () {
msg.removeClass('contact-error').empty();
});
$('#contact-container .contact-title').html('Vygdoma');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: '80px'
}, function () {
$('#contact-container .contact-loading').fadeIn(200, function () {
$.ajax({
url: 'data/contact.php',
data: $('#contact-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#contact-container .contact-loading').fadeOut(200, function () {
$('#contact-container .contact-title').html('Pavyko!');
msg.html(data).fadeIn(200);
});
},
error: contact.error
});
});
});
}
else {
if ($('#contact-container .contact-message:visible').length > 0) {
var msg = $('#contact-container .contact-message div');
msg.fadeOut(200, function () {
msg.empty();
contact.showError();
msg.fadeIn(200);
});
}
else {
$('#contact-container .contact-message').animate({
height: '30px'
}, contact.showError);
}
}
});
},
close: function (dialog) {
$('#contact-container .contact-message').fadeOut();
$('#contact-container .contact-title').html('Iki greito :)');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: 40
}, function () {
dialog.data.fadeOut(200, function () {
dialog.container.fadeOut(200, function () {
dialog.overlay.fadeOut(200, function () {
$.modal.close();
});
});
});
});
},
error: function (xhr) {
alert(xhr.statusText);
},
validate: function () {
contact.message = '';
if (!$('#contact-container #contact-name').val()) {
contact.message += 'Įveskite vardą';
}
var email = $('#contact-container #contact-email').val();
if (!email) {
contact.message += ' įveskite E-Paštą';
}
else {
if (!contact.validateEmail(email)) {
contact.message += 'Klaidingas E-Paštas. ';
}
}
if (!$('#contact-container #contact-subject').val()) {
contact.message += 'Įveskite nuorodą';
}
if (!$('#contact-container #contact-message').val()) {
contact.message += 'Komentaras yra būtinas.';
}
if (contact.message.length > 0) {
return false;
}
else {
return true;
}
},
validateEmail: function (email) {
var at = email.lastIndexOf("#");
// Make sure the at (#) sybmol exists and
// it is not the first or last character
if (at < 1 || (at + 1) === email.length)
return false;
// Make sure there aren't multiple periods together
if (/(\.{2,})/.test(email))
return false;
// Break up the local and domain portions
var local = email.substring(0, at);
var domain = email.substring(at + 1);
// Check lengths
if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
return false;
// Make sure local and domain don't start with or end with a period
if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
return false;
// Check for quoted-string addresses
// Since almost anything is allowed in a quoted-string address,
// we're just going to let them go through
if (!/^"(.+)"$/.test(local)) {
// It's a dot-string address...check for valid characters
if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
return false;
}
// Make sure domain contains only valid characters and at least one period
if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
return false;
return true;
},
showError: function () {
$('#contact-container .contact-message')
.html($('<div class="contact-error"></div>').append(contact.message))
.fadeIn(200);
}
};
contact.init();
});
- alert(document.URL)
- alert(Window.location.href)
- alert(document.location.href)
- alert(window.location.pathname)
Try any of these,it will give yout he current url.
You don't need to send it, if you're looking to have access to the name of the file the AJAX call was sent from in the php file that receives the request, you can use
$_SERVER['HTTP_REFERER'];
Which is useful if you're going to be receiving requests to that file from multiple locations.
You can get the current url in js with window.location.href
In general, you can get the url of the current page by using the window object. window.location.href will typically get you what you want, barring the case of frames within a page.
You can simply add this as a paramter to your ajax call, regardless of the page you're sending it to, or your back-end implementation.
Have a look at this example.
$(function () {
var postParams = {
"myUrl": window.location.href
};
$.post("/echo/json/", {
"json": JSON.stringify(postParams)
}, function (data) {
alert(JSON.stringify(data));
});
});

how to set edit form position and size in jqgrid combining with other properties

How to create jqgrid edit form at specified position and size which can changed in runtime?
Edit window postition should combined with other edit parameters in navGrid.
I tried code below but alert box does not appear and edit form is shown in default position.
var oldJqDnRstop,
editWindowParams = {
left: 10,
width: window.innerWidth-18,
top: 5,
height: 100
};
if ($.jqDnR) {
oldJqDnRstop = $.jqDnR.stop; // save original function
$.jqDnR.stop = function (e) {
var $dialog = $(e.target).parent(), dialogId = $dialog.attr("id"), position;
oldJqDnRstop.call(this, e); // call original function
if (typeof dialogId !== "string") {
return;
}
if (dialogId.substr(0, 11) === "editmodgrid") {
editWindowParams.width = $dialog.width();
position = $dialog.position();
editWindowParams.left = position.left;
editWindowParams.top = position.top;
}
};
}
$.extend($.jgrid.edit, {
closeAfterAdd: true,
recreateForm: true,
reloadAfterSubmit: false,
left: 10,
dataheight: '100%',
width: window.innerWidth-18
});
$grid.jqGrid("navGrid", "#grid_toppager", { edit: true },
{
top: function() { alert(editWindowParams.top); return editWindowParams.top; },
left: function() { return editWindowParams.left; },
width: function() { return editWindowParams.width; },
height: function() { return editWindowParams.height; },
afterSubmit: function (response, postdata) {
if (response.responseText.charAt(0) === '{') {
var json = $.parseJSON(response.responseText);
return [true, '', json.Id];
}
alert( decodeErrorMessage(response.responseText, '', ''));
return [false, decodeErrorMessage(response.responseText, '', ''), null];
},
beforeShowForm: function ($form) {
$("#tr_Info>td:eq(1)").attr("colspan", "2");
$("#tr_Info>td:eq(1)>textarea").css("width", "95%");
$("#tr_Info>td:eq(0)").hide();
$("#tr_Markused>td:eq(1)").attr("colspan", "2");
$("#tr_Markused>td:eq(1)>textarea").css("width", "95%");
$("#tr_Markused>td:eq(0)").hide();
beforeShowForm_base($form);
},
url: '/Edit',
closeAfterEdit: true,
onClose: function(){
$( ".ui-autocomplete-input").trigger("blur");
}
} );
The demo demonstrate the fixed code. It's modification of the demo from my previous answer. It uses the following code:
if ($.jqDnR) {
oldJqDnRstop = $.jqDnR.stop; // save original function
$.jqDnR.stop = function (e) {
var $dialog = $(e.target).parent(), dialogId = $dialog.attr("id"),
position, $form;
oldJqDnRstop.call(this, e); // call original function
if (typeof dialogId === "string") {
if (dialogId.substr(0,14) === "searchmodfbox_") {
// save the dialog position here
searchParams.width = $dialog.width();
position = $dialog.position();
searchParams.left = Math.max(0, position.left);
searchParams.top = Math.max(0, position.top);
} else if (dialogId.substr(0,7) === "editmod") {
// Add or Edit form
editParams.width = $dialog.width();
position = $dialog.position();
editParams.left = Math.max(0, position.left);
editParams.top = Math.max(0, position.top);
$form = $dialog.find("form.FormGrid");
if ($form.length > 0) {
editParams.dataheight = $form.height();
}
editParams.height = $dialog.height();
} else if (dialogId.substr(0,6) === "delmod") {
// Delete form
}
}
};
}

IE6-7 Javascript

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

Categories

Resources