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));
});
});
Related
I have written an javascript which load more when user scroll to bottom of a div .
This is the code I'm using :
var loadingSet = 0
var diMore = 1
var ob = 'default';
var db = 'desc' //نزولی
var doAppend = true
var loading= false;
function sort(){
diMore=1
ob = $('#ob').val();
db = $('#db').val();
loadingSet=-1
doAppend = false
loadMore()
}
function loadMore()
{
if (diMore ==1 && !loading){
var loading= false;
loadingSet++ ;
loading=true
$(document).ready(function() {
$(document).on({
ajaxStart: function() { $("#spinner").css("display", "block"); },
ajaxStop: function() { $("#spinner").fadeOut('slow'); }
});
$.ajax({
type: "POST",
url:baseUrl+ "getNewItems.php",
data: "limit=<?php echo $limit?>&stId=<?php echo $admins_id?>&status="+status+"&ob=" + ob +"&da="+ db +"&loadingSet="+loadingSet+"&submit=true",
success: function(msg){
str=$.trim(msg)
var More = str.split('##');
if (More[0] == 'n'){
diMore=0
}else{
$(window).bind('scroll', bindScroll2);
loading=false
}
if (doAppend){
$('#prodDiv').append(More[1])
}else{
doAppend=true
$('#prodDiv').html('')
$('#prodDiv').fadeOut(500, function() {
$(this).html(More[1]).fadeIn(500);
});
}
}
})
})
}
}
function bindScroll2(){
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('#mainDivCategory').offset().top + $('#mainDivCategory').outerHeight() - window.innerHeight) {
$(window).unbind('scroll');
if (!loading){
loadMore();
}
}
});
}
$(window).scroll(bindScroll2);
The problem is that when I scroll at the bottom of the div , the loadMore function is calling so many time at one . maybe about 50 -60 request at once.
What's the problem ?
Thanks
The question is very simple but also a bit theoretical.
Let's imagine you have a long JQuery script which modifies and animate the graphics of the web site. It's objective is to handle the UI. The UI has to be responsive so the real need for this JQuery is to mix some state of visualization (sportlist visible / not visible) with some need due to Responsive UI.
Thinking from an MVC / AngularJS point of view. How should a programmer handle that?
How to refactor JS / JQuery code to implement separation of concerns described by MVC / AngularJS?
I provide an example of JQuery code to speak over something concrete.
$.noConflict();
jQuery(document).ready(function ($) {
/*variables*/
var sliderMenuVisible = false;
/*dom object variables*/
var $document = $(document);
var $window = $(window);
var $pageHost = $(".page-host");
var $sportsList = $("#sports-list");
var $mainBody = $("#mainBody");
var $toTopButtonContainer = $('#to-top-button-container');
/*eventHandlers*/
var displayError = function (form, error) {
$("#error").html(error).removeClass("hidden");
};
var calculatePageLayout = function () {
$pageHost.height($(window).height());
if ($window.width() > 697) {
$sportsList.removeAttr("style");
$mainBody
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
if ($(".betslip-access-button")[0]) {
$(".betslip-access-button").fadeIn(500);
}
sliderMenuVisible = false;
} else {
$(".betslip-access-button").fadeOut(500);
}
};
var formSubmitHandler = function (e) {
var $form = $(this);
// We check if jQuery.validator exists on the form
if (!$form.valid || $form.valid()) {
$.post($form.attr("action"), $form.serializeArray())
.done(function (json) {
json = json || {};
// In case of success, we redirect to the provided URL or the same page.
if (json.success) {
window.location = json.redirect || location.href;
} else if (json.error) {
displayError($form, json.error);
}
})
.error(function () {
displayError($form, "Login service not available, please try again later.");
});
}
// Prevent the normal behavior since we opened the dialog
e.preventDefault();
};
//preliminary functions//
$window.on("load", calculatePageLayout);
$window.on("resize", calculatePageLayout);
//$(document).on("click","a",function (event) {
// event.preventDefault();
// window.location = $(this).attr("href");
//});
/*evet listeners*/
$("#login-form").submit(formSubmitHandler);
$("section.navigation").on("shown hidden", ".collapse", function (e) {
var $icon = $(this).parent().children("button").children("i").first();
if (!$icon.hasClass("icon-spin")) {
if (e.type === "shown") {
$icon.removeClass("icon-caret-right").addClass("icon-caret-down");
} else {
$icon.removeClass("icon-caret-down").addClass("icon-caret-right");
}
}
toggleBackToTopButton();
e.stopPropagation();
});
$(".collapse[data-src]").on("show", function () {
var $this = $(this);
if (!$this.data("loaded")) {
var $icon = $this.parent().children("button").children("i").first();
$icon.removeClass("icon-caret-right icon-caret-down").addClass("icon-refresh icon-spin");
console.log("added class - " + $icon.parent().html());
$this.load($this.data("src"), function () {
$this.data("loaded", true);
$icon.removeClass("icon-refresh icon-spin icon-caret-right").addClass("icon-caret-down");
console.log("removed class - " + $icon.parent().html());
});
}
toggleBackToTopButton();
});
$("#sports-list-button").on("click", function (e)
{
if (!sliderMenuVisible)
{
$sportsList.animate({ left: "0" }, 500);
$mainBody.animate({ left: "85%" }, 500)
.bind('touchmove', function (e2) { e2.preventDefault(); })
.addClass('stop-scroll');
$(".betslip-access-button").fadeOut(500);
sliderMenuVisible = true;
}
else
{
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500).removeAttr("style")
.unbind('touchmove').removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
}
e.preventDefault();
});
$mainBody.on("click", function (e) {
if (sliderMenuVisible) {
$sportsList.animate({ left: "-85%" }, 500).removeAttr("style");
$mainBody.animate({ left: "0" }, 500)
.removeAttr("style")
.unbind('touchmove')
.removeClass('stop-scroll');
$(".betslip-access-button").fadeIn(500);
sliderMenuVisible = false;
e.stopPropagation();
e.preventDefault();
}
});
$document.on("click", "div.event-info", function () {
if (!sliderMenuVisible) {
var url = $(this).data("url");
if (url) {
window.location = url;
}
}
});
function whatDecimalSeparator() {
var n = 1.1;
n = n.toLocaleString().substring(1, 2);
return n;
}
function getValue(textBox) {
var value = textBox.val();
var separator = whatDecimalSeparator();
var old = separator == "," ? "." : ",";
var converted = parseFloat(value.replace(old, separator));
return converted;
}
$(document).on("click", "a.selection", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/Add/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
var urlHoveringBtn = "/" + _language + '/BetSlip/AddHoveringButton/' + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(urlHoveringBtn).done(function (dataBtn) {
if ($(".betslip-access-button").length == 0 && dataBtn.length > 0) {
$("body").append(dataBtn);
}
});
$.ajax(url).done(function (data) {
if ($(".betslip-access").length == 0 && data.length > 0) {
$(".navbar").append(data);
$pageHost.addClass("betslipLinkInHeader");
var placeBetText = $("#live-betslip-popup").data("placebettext");
var continueText = $("#live-betslip-popup").data("continuetext");
var useQuickBetLive = $("#live-betslip-popup").data("usequickbetlive").toLowerCase() == "true";
var useQuickBetPrematch = $("#live-betslip-popup").data("usequickbetprematch").toLowerCase() == "true";
if ((isLive && useQuickBetLive) || (!isLive && useQuickBetPrematch)) {
var dialog = $("#live-betslip-popup").dialog({
modal: true,
dialogClass: "fixed-dialog"
});
dialog.dialog("option", "buttons", [
{
text: placeBetText,
click: function () {
var placeBetUrl = "/" + _language + "/BetSlip/QuickBet?amount=" + getValue($("#live-betslip-popup-amount")) + "&live=" + $this.data("live");
window.location = placeBetUrl;
}
},
{
text: continueText,
click: function () {
dialog.dialog("close");
}
}
]);
}
}
if (data.length > 0) {
$this.addClass("in-betslip");
}
});
e.preventDefault();
});
$(document).on("click", "a.selection.in-betslip", function (e) {
if (sliderMenuVisible) {
return;
}
var $this = $(this);
var isLive = $this.data("live");
var url = "/" + _language + "/BetSlip/RemoveAjax/" + $this.data("selection") + "?odds=" + $this.data("odds") + "&live=" + isLive;
$.ajax(url).done(function (data) {
if (data.success) {
$this.removeClass("in-betslip");
if (data.selections == 0) {
$(".betslip-access").remove();
$(".betslip-access-button").remove();
$(".page-host").removeClass("betslipLinkInHeader");
}
}
});
e.preventDefault();
});
$("section.betslip .total-stake button.live-betslip-popup-plusminus").click(function (e) {
if (sliderMenuVisible) {
return;
}
e.preventDefault();
var action = $(this).data("action");
var amount = parseFloat($(this).data("amount"));
if (!isNumeric(amount)) amount = 1;
var totalStake = $("#live-betslip-popup-amount").val();
if (isNumeric(totalStake)) {
totalStake = parseFloat(totalStake);
} else {
totalStake = 0;
}
if (action == "decrease") {
if (totalStake < 1.21) {
totalStake = 1.21;
}
totalStake -= amount;
} else if (action == "increase") {
totalStake += amount;
}
$("#live-betslip-popup-amount").val(totalStake);
});
toggleBackToTopButton();
function toggleBackToTopButton() {
isScrollable() ? $toTopButtonContainer.show() : $toTopButtonContainer.hide();
}
$("#to-top-button").on("click", function () { $("#mainBody").animate({ scrollTop: 0 }); });
function isScrollable() {
return $("section.navigation").height() > $(window).height() + 93;
}
var isNumeric = function (string) {
return !isNaN(string) && isFinite(string) && string != "";
};
function enableQuickBet() {
}
});
My steps in such cases are:
First of all write (at least) one controller
Replace all eventhandler with ng-directives (ng-click most of all)
Pull the view state out of the controller with ng-style and ng-class. In most of all cases ng-show and ng-hide will be sufficed
If there is code that will be used more than once, consider writing a directive.
And code that has nothing todo with the view state - put the code in a service
write unit tests (i guess there is no one until now:) )
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
I have the following problem in js that I am working:
Uncaught ReferenceError: slideshow_animate is not defined (anonymous
function)
The function that refers to that is:
function slideshow_animate() {
if(!animation.auto_animate) return;
var next_slide = $('.item-slide.active').next();
if(!next_slide.length) {
next_slide = $('#item-slide-1');
}
next_slide.click();
}
I have another website where if I is working but it seems that in this application I am having a problem with slideshowa_animate, attached the full code for reference:
(function ($, Drupal) {
Drupal.behaviors.lek7_zen_theme = {
attach: function(context, settings) {
$(document).ready(function(){
var i = 1;
$('.item-slide').each(function(key, value) {
$(value).attr('id', 'item-slide-'+i);
i++;
});
$('.slide_caption').hide();
$('#item-slide-1 > .slide_caption').show();
$('#item-slide-1').addClass('active');
$('.item-slide').not('.active').children('.slide_image_slice').show();
});
var animation = {
'auto_animate': true,
'auto_animate_delay': 8000,
'auto_animate_id': '',
'caption_speed': 'fast',
//'panel_speed': 'slow',
'panel_speed': 1000,
'panel_easing': 'easeInOutCubic'
}
$('.item-slide')
.bind('open', function(){
if(! $(this).hasClass('open')){
$(this).next().trigger('open');
$(this).addClass('open');
$(this).animate({right: "-=769px"}, animation.panel_speed, animation.panel_easing, function(){display_slices();});
}
else{
$(this).prev().trigger('close');
}
$(this).siblings().removeClass('active');
$(this).addClass('active');
setTimeout(function(){hide_slices()},1);
display_caption();
})
.bind('close', function(){
if($(this).hasClass('open')){
$(this).removeClass('open');
$(this).animate({right: "+=769px"}, animation.panel_speed, animation.panel_easing, function(){display_slices();});
$(this).prev().trigger('close');
}
});
$('.item-slide')
.hoverIntent(
function() {
animation.auto_animate = false;
trigger_accordion($(this));
},
function() {
animation.auto_animate = true;
clearInterval(animation.auto_animate_id);
animation.auto_animate_id = setInterval('slideshow_animate()', animation.auto_animate_delay);
}
)
.click(function() {
trigger_accordion($(this));
});
animation.auto_animate_id = setInterval('slideshow_animate()', animation.auto_animate_delay);
function trigger_accordion(itemSlide) {
if(!(itemSlide.is(':animated'))) {
itemSlide.trigger('open');
}
}
function display_caption() {
$('.slide_caption').each(function() {
if(!($(this).parent().hasClass('active'))) {
$(this).fadeOut('fast', function() {
$('.item-slide.active > .slide_caption').fadeIn(animation.caption_speed);
});
}
});
}
function hide_slices() {
$('.slide_image_slice').each(function() {
if($(this).parent().hasClass('active')) {
$(this).fadeOut('fast');
}
});
}
function display_slices() {
$('.slide_image_slice').each(function() {
if(!$(this).parent().hasClass('active') && !$(this).is(":visible")) {
$(this).fadeIn('fast');
}
});
}
function slideshow_animate() {
if(!animation.auto_animate) return;
var next_slide = $('.item-slide.active').next();
if(!next_slide.length) {
next_slide = $('#item-slide-1');
}
next_slide.click();
}
}
};
})(jQuery, Drupal);
When you use animation.auto_animate_id = setInterval('slideshow_animate()', animation.auto_animate_delay); the function is evaluated in the global scope where the function slideshow_animate does not exists since it is in a closure scope
Try
animation.auto_animate_id = setInterval(slideshow_animate, animation.auto_animate_delay);
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.