Resizing does not work in paperjs 0.11.8 but works for 0.9.25 - paperjs

I am trying to resize a rectangle in paper.js. I am able to do it for older versions of paperjs (like 0.9.25) but it is not working for the latest version 0.11.8. I am not sure why this is happening, any help would be highly appreciated.
Here is the Sketch link, you may select the version to 0.9.25 where it works and 0.11.8 where it doesnt work.
Sketch
Here is my code:
var hitOptions = {
segments: true,
stroke: true,
fill: true,
tolerance: 1
};
project.currentStyle = {
fillColor: 'green',
strokeColor: 'black'
};
var rect_a = new Path.Rectangle(new Point(50, 50), 50);
var segment, path, hitType;
var clickPos = null;
var movePath = false;
var minHeight = 1;
var minWidth = 1;
function onMouseDown(event) {
segment = path = null;
var hitResult = project.hitTest(event.point, hitOptions);
if (!hitResult)
return;
hitType = hitResult.type;
if (event.modifiers.shift) {
if (hitResult.type == 'segment') {
hitResult.segment.remove();
};
return;
}
if (hitResult) {
path = hitResult.item;
if (hitResult.type == 'segment') {
segment = hitResult.segment;
}
}
movePath = hitResult.type == 'fill';
if (movePath) {
project.activeLayer.addChild(hitResult.item);
}
clickPos = checkHitPosition(event);
}
function onMouseMove(event) {
changeCursor(event);
project.activeLayer.selected = false;
if (event.item)
event.item.selected = true;
}
function onMouseDrag(event) {
if (hitType == "stroke" || hitType == "segment") {
resizeRectangle(path, event);
} else {
path.position += event.delta;
}
}
function resizeRectangle(path, event) {
switch(clickPos) {
case "SE" :
resizeBottom(path, event);
resizeRight(path, event);
break;
case "NE" :
resizeTop(path, event);
resizeRight(path, event);
break;
case "SW" :
resizeBottom(path, event);
resizeLeft(path, event);
break;
case "NW" :
resizeTop(path, event);
resizeLeft(path, event);
break;
case "S" :
resizeBottom(path, event);
break;
case "N" :
resizeTop(path, event);
break;
case "E" :
resizeRight(path, event);
break;
case "W" :
resizeLeft(path, event);
break;
}
}
function resizeTop(path, event) {
if(path.bounds.height >= minHeight) {
var adj = Math.min(event.delta.y, path.bounds.height-minHeight);
path.bounds.top += adj;
}
}
function resizeBottom(path, event) {
if(path.bounds.height >= minHeight) {
path.bounds.bottom += event.delta.y;
}
}
function resizeLeft(path, event) {
if(path.bounds.width >= minWidth) {
path.bounds.left += event.delta.x;
}
}
function resizeRight(path, event) {
if(path.bounds.width >= minWidth) {
path.bounds.right += event.delta.x;
}
}
function checkHitPosition(event) {
var hitResult = project.hitTest(event.point, hitOptions);
var clickPosition = null;
if (hitResult) {
if (hitResult.type == 'stroke' || hitResult.type == 'segment') {
var bounds = hitResult.item.bounds;
var point = hitResult.point;
if (bounds.top == point.y) {
clickPosition = "N";
}
if (bounds.bottom == point.y) {
clickPosition = "S";
}
if (bounds.left == point.x) {
clickPosition = "W";
}
if (bounds.right == point.x) {
clickPosition = "E";
}
if (bounds.top == point.y && bounds.left == point.x) {
clickPosition = "NW";
}
if (bounds.top == point.y && bounds.right == point.x) {
clickPosition = "NE";
}
if (bounds.bottom == point.y && bounds.left == point.x) {
clickPosition = "SW";
}
if (bounds.bottom == point.y && bounds.right == point.x) {
clickPosition = "SE";
}
} else {
clickPosition = "C";
}
}
return clickPosition;
};
function changeCursor(event) {
var hitPosition = checkHitPosition(event);
if(hitPosition == null ) {
document.body.style.cursor = "auto";
} else {
if (hitPosition == "C") {
document.body.style.cursor = "all-scroll";
} else {
document.body.style.cursor = hitPosition + "-resize";
}
}
}

helloworld,
If you want to resize/scale your path, I recommend using the Path.scalemethod (http://paperjs.org/reference/item/#scale-hor-ver).
To apply this on your example, replace your current resizing methods with:
function resizeTop(path, event) {
if(path.bounds.height >= minHeight) {
var relH = (event.point.y - (path.bounds.bottomCenter.y)) / path.bounds.height;
path.scale(1, -relH, path.bounds.bottomCenter)
}
}
function resizeBottom(path, event) {
if(path.bounds.height >= minHeight) {
var relH = (event.point.y - (path.bounds.topCenter.y)) / path.bounds.height;
path.scale(1, relH, path.bounds.topCenter)
}
}
function resizeLeft(path, event) {
if(path.bounds.width >= minWidth) {
var relW = (event.point.x - (path.bounds.rightCenter.x)) / path.bounds.width;
path.scale(-relW, 1, path.bounds.rightCenter)
}
}
function resizeRight(path, event) {
if(path.bounds.width >= minWidth) {
var relW = (event.point.x - (path.bounds.leftCenter.x)) / path.bounds.width;
path.scale(relW, 1, path.bounds.leftCenter)
}
}
Have a nice day!
-- edit --
I remade your sketch and replaced the code, sketch, which works with every version.

Related

How to draw a Curved line between two Points using Here Maps?

Need suggestions on how to add Curved Polyline using Here Maps Javascript API ?
There is no any straight way, but you can use following formula:
var D2R = Math.PI / 180;
var R2D = 180 / Math.PI;
var Coord = function(lon, lat) {
this.lon = lon;
this.lat = lat;
this.x = D2R * lon;
this.y = D2R * lat;
};
Coord.prototype.view = function() {
return String(this.lon).slice(0, 4) + ',' + String(this.lat).slice(0, 4);
};
Coord.prototype.antipode = function() {
var anti_lat = -1 * this.lat;
var anti_lon = (this.lon < 0) ? 180 + this.lon : (180 - this.lon) * -1;
return new Coord(anti_lon, anti_lat);
};
var LineString = function() {
this.coords = [];
this.length = 0;
};
LineString.prototype.move_to = function(coord) {
this.length++;
this.coords.push(coord);
};
var Arc = function(properties) {
this.properties = properties || {};
this.geometries = [];
};
Arc.prototype.json = function() {
if (this.geometries.length <= 0) {
return { 'geometry': { 'type': 'LineString', 'coordinates': null }, 'type': 'Feature', 'properties': this.properties };
} else if (this.geometries.length == 1) {
return { 'geometry': { 'type': 'LineString', 'coordinates': this.geometries[0].coords }, 'type': 'Feature', 'properties': this.properties };
} else {
var multiline = [];
for (var i = 0; i < this.geometries.length; i++) {
multiline.push(this.geometries[i].coords);
}
return { 'geometry': { 'type': 'MultiLineString', 'coordinates': multiline }, 'type': 'Feature', 'properties': this.properties };
}
};
Arc.prototype.strip = function() {
var s = H.geo.Strip ? new H.geo.Strip() : new H.geo.LineString();
for (var i = 0; i < this.geometries.length; i++) {
if (this.geometries[i].coords.lenght !== 0) {
var coords = this.geometries[i].coords;
for (var j = 0; j < coords.length; j++) {
var p = new H.geo.Point(coords[j][1], coords[j][0]);
s.pushPoint(p);
}
}
}
return s;
}
For detailed example, I have created a sample, please check - https://demo.support.here.com/examples/v3.1/geodesic_polyline

Fullcalendar recurring events limits (using dow)

I have been trying to make recurring events in fullcalendar, I really find dow feature helpful, but I really want to add date ranges to it.
In other words, dow : [1] will repeat a task for every single Monday, the problems is, I want to make it visible only in a date range I set.
You can not set ranges by using dow, you have to perform some custom functionality.
Lets suppose that you have fetched events data from your database which contains multiple event objects. each event object has start date end date property and also to and from properties which contains date range , isRecurring is a Boolean property which we will add true in case of recurring events otherwise it will be false.
Remember the recurring events take start and end time without date, you only need to give them time slots, like start = "16:00" and end = "20:00" You can extract time by using moment js like i did while initializing my event object
{
title:'Recurring Event',
start: moment.utc(event.start).format('HH:mm'),
end: moment.utc(event.end).format('HH:mm'),
isRecurrring: event.isRecurring,
ranges: [{
start: moment(event.from),
end: moment(event.to),
}],
}
I have used moment.utc() to ignore the timezone.
Now override the eventRender function while initializing your fullCalendar. Your eventRender function will be
eventRender: function(event, element, view){
if (event.isRecurrring) {
return (event.ranges.filter(function(range){
return (moment(event.start).isBefore(range.end) &&
moment(event.end).isAfter(range.start));
}).length) > 0;
}
}
You coulded set ranges as this example:
repeatingEvents.push({
title: "From: " + inputDateStart + " To: " + inputDateFinish,
start: vm.timeStart,
end: vm.timeFinish,
dow: listDay,
ranges: [{
start: dateStart,
end: dateFinish
}]
})
$("#calendar").fullCalendar("refetchEvents");
So you can use both "dow" and "ranges". Hope help for you!
function createCalendar() {
vm.uiConfig = timeProfileFactory.getCalendarConfig();
vm.uiConfig.calendar.eventClick = eventClick;
vm.uiConfig.calendar.eventDrop = alertOnDrop;
vm.uiConfig.calendar.eventResize = alertOnResize;
vm.uiConfig.calendar.eventRender = eventRender;
vm.uiConfig.calendar.select = selectSlot;
vm.uiConfig.calendar.header.center = "title";
vm.events = function(start, end, timezone, callback) {
callback(repeatingEvents);
}
vm.eventSources = [vm.events];
};
function selectSlot(start, end, jsEvent, view) {
var allDay = !start.hasTime() && !end.hasTime();
var offset = ((new Date()).getTimezoneOffset())/60;
var dateStart = (new Date(start)).setHours(0, 0, 0, 0);
dateStart = new Date(dateStart);
dateStart.setHours(dateStart.getHours() - offset);
dateStart = dateStart.toISOString();
var timeStart = (new Date(start)).toISOString();
var timeEnd = (new Date(end)).toISOString();
timeStart = timeStart.split('T')[0];
timeEnd = timeEnd.split('T')[0];
var length = repeatingEvents.length;
if(positionEvent == -1 || repeatingEvents.length == 0) {
positionEvent = 0;
} else {
positionEvent = repeatingEvents[length - 1].position + 1;
}
repeatingEvents.push({
title: "From: " + start.format("DD/MM/YYYY"),
start: start.format("HH:mm"),
end: end.format("HH:mm"),
dow: [new Date(start).getDay()],
ranges: [{
start: dateStart,
end: null
}],
position: positionEvent,
allDay: false
});
length++;
if(repeatingEvents[length - 1].end == "00:00") {
repeatingEvents[length - 1].end = "24:00";
}
if(allDay) {
repeatingEvents[length - 1].allDay = true;
repeatingEvents[length - 1].start = null;
repeatingEvents[length - 1].end = null;
}
$("#calendar").fullCalendar("refetchEvents");
};
function eventClick(event, date, jsEvent, view) {
isOpenDialog = true;
for(var i = 0; i < repeatingEvents.length; i++) {
if(repeatingEvents[i].position == event.position && isOpenDialog) {
selectIndex = i;
vm.timeStart = repeatingEvents[i].start;
vm.timeFinish = repeatingEvents[i].end;
vm.dateStart = repeatingEvents[i].title.split(' ')[1];
if(repeatingEvents[i].ranges[0].end == null) {
vm.dateFinish = "";
vm.radioValue = "never";
} else {
vm.dateFinish = repeatingEvents[i].title.split(' ')[3];
vm.radioValue = "on";
}
angular.forEach(vm.checkDays, function(item) {
item.checked = false;
});
angular.forEach(event.dow, function(index) {
vm.checkDays[index].checked = true;
})
openDialog();
break;
}
}
};
function alertOnResize(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
var timeFinish = event.end.format("HH:mm");
if(timeFinish == "00:00") {
timeFinish = "24:00";
}
repeatingEvents[i].end = timeFinish;
break;
}
}
$("#calendar").fullCalendar("refetchEvents");
};
function alertOnDrop(event, delta, revertFunc, jsEvent, ui, view) {
for(var i in repeatingEvents) {
if(repeatingEvents[i].position == event.position) {
if(repeatingEvents[i].allDay || event.allDay) {
revertFunc();
} else {
var timeStart = event.start.format("HH:mm");
var timeFinish = event.end.format("HH:mm");
var dateStart = repeatingEvents[i].ranges[0].start;
var dateFinish = repeatingEvents[i].ranges[0].end;
var oldTimeStart = repeatingEvents[i].start.split(':')[0]*3600 + repeatingEvents[i].start.split(':')[1]*60;
var newTimeStart = timeStart.split(':')[0]*3600 + timeStart.split(':')[1]*60;
var deltaHour = newTimeStart - oldTimeStart;
var deltaDay = (delta/1000 - deltaHour)/86400;
dateStart = new Date(dateStart);
dateStart.setDate(dateStart.getDate() + deltaDay);
dateStart = dateStart.toISOString();
var title;
if(dateFinish != null) {
dateFinish = new Date(dateFinish);
dateFinish.setDate(dateFinish.getDate() + deltaDay);
dateFinish = dateFinish.toISOString();
title = "From: " + moment(dateStart).format("DD/MM/YYYY") + " To: " + moment(dateFinish).format("DD/MM/YYYY");
} else {
title = "From: " + moment(dateStart).format("DD/MM/YYYY");
}
for(var j in event.dow) {
repeatingEvents[i].dow[j] = parseInt(repeatingEvents[i].dow[j]) + deltaDay;
if(repeatingEvents[i].dow[j] > 6) {
repeatingEvents[i].dow.splice(j, 1);
}
}
repeatingEvents[i].start = timeStart;
repeatingEvents[i].end = timeFinish;
repeatingEvents[i].ranges[0].start = dateStart;
repeatingEvents[i].ranges[0].end = dateFinish;
repeatingEvents[i].title = title;
if(timeFinish == "00:00") {
repeatingEvents[i].end = "24:00";
}
$("#calendar").fullCalendar("refetchEvents");
}
break;
}
}
};
function eventRender(event, element, view) {
var removeEvent = $("<i class='removeEvent icons8-delete pull-right'></i>");
removeEvent.on("click", function() {
isOpenDialog = false;
vm.removeEvent(event);
});
element.find(".fc-content").prepend(removeEvent);
var result;
if(event.ranges[0].end == null) {
result = (event.ranges.filter(function(range) {
var startConvert = (new Date(event.start)).toISOString();
return (event.start.isAfter(range.start) || startConvert == range.start);
}).length) > 0;
} else {
result = (event.ranges.filter(function(range) {
return (event.start.isBefore(range.end) && event.end.isAfter(range.start));
}).length) > 0;
}
return result;
};

Set fixed width to Nivo Slider

I've installed Nivo Slider using the code from the demo included in the free download.
All of the images I am including in the slider are 800 pixels wide.
However, they are being resized to 1440 pixels wide. Extra code is being inserted:
<img src="images/bar.jpg" data-thumb="images/bar.jpg" alt="" title="" style="display: none; width: 1440px;">
I have searched the CSS and JS and can find no mention of 1440.
Where is this width being set?
Nivo Slider is responsive by default, if you want to limit the sliders width, use the below class in your CSS
.slider-wrapper.theme-default {
width: 800px; /* Desired width */
}
The above will work if you are using default theme of nivo slider, if you are using some other theme, than simply change the .theme-default to theme specific class which is assigned to the slider wrapper.
Use my custom nivo script code
/*
* jQuery Nivo Slider v2.5.1
* http://nivo.dev7studios.com
*
* Copyright 2011, Gilbert Pellegrom
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* March 2010
*/
(function($) {
var NivoSlider = function(element, options) {
var settings = $.extend({}, $.fn.nivoSlider.defaults, options);
var vars = {
currentSlide : 0,
currentImage : '',
totalSlides : 0,
randAnim : '',
running : false,
paused : false,
stop : false
};
var slider = $(element);
slider.data('nivo:vars', vars);
slider.css('position', 'relative');
slider.addClass('nivoSlider');
var kids = slider.children();
kids.each(function() {
var child = $(this);
var link = '';
if (!child.is('img')) {
if (child.is('a')) {
child.addClass('nivo-imageLink');
link = child;
}
child = child.find('img:first');
}
var childWidth = child.width();
if (childWidth == 0)
childWidth = child.attr('width');
var childHeight = child.height();
if (childHeight == 0)
childHeight = child.attr('height');
if (childWidth > slider.width()) {
slider.width(childWidth);
}
if (childHeight > slider.height()) {
slider.height(childHeight);
}
if (link != '') {
link.css('display', 'none');
}
child.css('display', 'none');
vars.totalSlides++;
});
if (settings.startSlide > 0) {
if (settings.startSlide >= vars.totalSlides)
settings.startSlide = vars.totalSlides - 1;
vars.currentSlide = settings.startSlide;
}
if ($(kids[vars.currentSlide]).is('img')) {
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
if ($(kids[vars.currentSlide]).is('a')) {
$(kids[vars.currentSlide]).css('display', 'block');
}
slider.css({
'background' : 'url("' + vars.currentImage.attr('src') + '") no-repeat',
'background-size' : settings.backgroundSize
});
slider.append($('<div class="nivo-caption"><p></p></div>').css({
display : 'none',
opacity : settings.captionOpacity
}));
var processCaption = function(settings) {
var nivoCaption = $('.nivo-caption', slider);
if (vars.currentImage.attr('title') != '') {
var title = vars.currentImage.attr('title');
if (title.substr(0, 1) == '#')
title = $(title).html();
if (nivoCaption.css('display') == 'block') {
nivoCaption.find('p').fadeOut(settings.animSpeed, function() {
$(this).html(title);
$(this).fadeIn(settings.animSpeed);
});
} else {
nivoCaption.find('p').html(title);
}
nivoCaption.fadeIn(settings.animSpeed);
} else {
nivoCaption.fadeOut(settings.animSpeed);
}
}
processCaption(settings);
var timer = 0;
if (!settings.manualAdvance && kids.length > 1) {
timer = setInterval(function() {
nivoRun(slider, kids, settings, false);
}, settings.pauseTime);
}
if (settings.directionNav) {
slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">' + settings.prevText + '</a><a class="nivo-nextNav">' + settings.nextText + '</a></div>');
if (settings.directionNavHide) {
$('.nivo-directionNav', slider).hide();
slider.hover(function() {
$('.nivo-directionNav', slider).show();
}, function() {
$('.nivo-directionNav', slider).hide();
});
}
$('a.nivo-prevNav', slider).live('click', function() {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
$('a.nivo-nextNav', slider).live('click', function() {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
});
}
if (settings.controlNav) {
var nivoControl = $('<div class="nivo-controlNav"></div>');
slider.append(nivoControl);
for (var i = 0; i < kids.length; i++) {
if (settings.controlNavThumbs) {
var child = kids.eq(i);
if (!child.is('img')) {
child = child.find('img:first');
}
if (settings.controlNavThumbsFromRel) {
nivoControl.append('<a class="nivo-control" rel="' + i + '"><img src="' + child.attr('rel') + '" alt="" /></a>');
} else {
nivoControl.append('<a class="nivo-control" rel="' + i + '"><img src="' + child.attr('src').replace(settings.controlNavThumbsSearch, settings.controlNavThumbsReplace) + '" alt="" /></a>');
}
} else {
nivoControl.append('<a class="nivo-control" rel="' + i + '">' + (i + 1) + '</a>');
}
}
$('.nivo-controlNav a:eq(' + vars.currentSlide + ')', slider).addClass('active');
$('.nivo-controlNav a', slider).live('click', function() {
if (vars.running)
return false;
if ($(this).hasClass('active'))
return false;
clearInterval(timer);
timer = '';
slider.css({
'background' : 'url("' + vars.currentImage.attr('src') + '") no-repeat',
'background-size' : settings.backgroundSize
});
vars.currentSlide = $(this).attr('rel') - 1;
nivoRun(slider, kids, settings, 'control');
});
}
if (settings.keyboardNav) {
$(window).keypress(function(event) {
if (event.keyCode == '37') {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
}
if (event.keyCode == '39') {
if (vars.running)
return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
}
});
}
if (settings.pauseOnHover) {
slider.hover(function() {
vars.paused = true;
clearInterval(timer);
timer = '';
}, function() {
vars.paused = false;
if (timer == '' && !settings.manualAdvance) {
timer = setInterval(function() {
nivoRun(slider, kids, settings, false);
}, settings.pauseTime);
}
});
}
slider.bind('nivo:animFinished', function() {
vars.running = false;
$(kids).each(function() {
if ($(this).is('a')) {
$(this).css('display', 'none');
}
});
if ($(kids[vars.currentSlide]).is('a')) {
$(kids[vars.currentSlide]).css('display', 'block');
}
if (timer == '' && !vars.paused && !settings.manualAdvance) {
timer = setInterval(function() {
nivoRun(slider, kids, settings, false);
}, settings.pauseTime);
}
settings.afterChange.call(this);
});
var createSlices = function(slider, settings, vars) {
for (var i = 0; i < settings.slices; i++) {
var sliceWidth = Math.round(slider.width() / settings.slices);
if (i == settings.slices - 1) {
slider.append($('<div class="nivo-slice"></div>').css({
left : (sliceWidth * i) + 'px',
width : (slider.width() - (sliceWidth * i)) + 'px',
height : '0px',
opacity : '0',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((sliceWidth + (i * sliceWidth)) - sliceWidth) + 'px 0%',
'background-size': settings.backgroundSize
}));
} else {
slider.append($('<div class="nivo-slice"></div>').css({
left : (sliceWidth * i) + 'px',
width : sliceWidth + 'px',
height : '0px',
opacity : '0',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((sliceWidth + (i * sliceWidth)) - sliceWidth) + 'px 0%',
'background-size': settings.backgroundSize
}));
}
}
}
var createBoxes = function(slider, settings, vars) {
var boxWidth = Math.round(slider.width() / settings.boxCols);
var boxHeight = Math.round(slider.height() / settings.boxRows);
for (var rows = 0; rows < settings.boxRows; rows++) {
for (var cols = 0; cols < settings.boxCols; cols++) {
if (cols == settings.boxCols - 1) {
slider.append($('<div class="nivo-box"></div>').css({
opacity : 0,
left : (boxWidth * cols) + 'px',
top : (boxHeight * rows) + 'px',
width : (slider.width() - (boxWidth * cols)) + 'px',
height : boxHeight + 'px',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((boxWidth + (cols * boxWidth)) - boxWidth) + 'px -' + ((boxHeight + (rows * boxHeight)) - boxHeight) + 'px',
'background-size': settings.backgroundSize
}));
} else {
slider.append($('<div class="nivo-box"></div>').css({
opacity : 0,
left : (boxWidth * cols) + 'px',
top : (boxHeight * rows) + 'px',
width : boxWidth + 'px',
height : boxHeight + 'px',
background : 'url("' + vars.currentImage.attr('src') + '") no-repeat -' + ((boxWidth + (cols * boxWidth)) - boxWidth) + 'px -' + ((boxHeight + (rows * boxHeight)) - boxHeight) + 'px',
'background-size': settings.backgroundSize
}));
}
}
}
}
var nivoRun = function(slider, kids, settings, nudge) {
var vars = slider.data('nivo:vars');
if (vars && (vars.currentSlide == vars.totalSlides - 1)) {
settings.lastSlide.call(this);
}
if ((!vars || vars.stop) && !nudge)
return false;
settings.beforeChange.call(this);
if (!nudge) {
slider.css({'background':'url("' + vars.currentImage.attr('src') + '") no-repeat','background-size': settings.backgroundSize });
} else {
if (nudge == 'prev') {
slider.css({'background':'url("' + vars.currentImage.attr('src') + '") no-repeat','background-size': settings.backgroundSize });
}
if (nudge == 'next') {
slider.css({'background':'url("' + vars.currentImage.attr('src') + '") no-repeat','background-size': settings.backgroundSize });
}
}
vars.currentSlide++;
if (vars.currentSlide == vars.totalSlides) {
vars.currentSlide = 0;
settings.slideshowEnd.call(this);
}
if (vars.currentSlide < 0)
vars.currentSlide = (vars.totalSlides - 1);
if ($(kids[vars.currentSlide]).is('img')) {
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
if (settings.controlNav) {
$('.nivo-controlNav a', slider).removeClass('active');
$('.nivo-controlNav a:eq(' + vars.currentSlide + ')', slider).addClass('active');
}
processCaption(settings);
$('.nivo-slice', slider).remove();
$('.nivo-box', slider).remove();
if (settings.effect == 'random') {
var anims = new Array('sliceDownRight', 'sliceDownLeft', 'sliceUpRight', 'sliceUpLeft', 'sliceUpDown', 'sliceUpDownLeft', 'fold', 'fade', 'boxRandom', 'boxRain', 'boxRainReverse', 'boxRainGrow', 'boxRainGrowReverse');
vars.randAnim = anims[Math.floor(Math.random() * (anims.length + 1))];
if (vars.randAnim == undefined)
vars.randAnim = 'fade';
}
if (settings.effect.indexOf(',') != -1) {
var anims = settings.effect.split(',');
vars.randAnim = anims[Math.floor(Math.random() * (anims.length))];
if (vars.randAnim == undefined)
vars.randAnim = 'fade';
}
vars.running = true;
if (settings.effect == 'sliceDown' || settings.effect == 'sliceDownRight' || vars.randAnim == 'sliceDownRight' || settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if (settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft')
slices = $('.nivo-slice', slider)._reverse();
slices.each(function() {
var slice = $(this);
slice.css({
'top' : '0px'
});
if (i == settings.slices - 1) {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if (settings.effect == 'sliceUp' || settings.effect == 'sliceUpRight' || vars.randAnim == 'sliceUpRight' || settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if (settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft')
slices = $('.nivo-slice', slider)._reverse();
slices.each(function() {
var slice = $(this);
slice.css({
'bottom' : '0px'
});
if (i == settings.slices - 1) {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if (settings.effect == 'sliceUpDown' || settings.effect == 'sliceUpDownRight' || vars.randAnim == 'sliceUpDown' || settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var v = 0;
var slices = $('.nivo-slice', slider);
if (settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft')
slices = $('.nivo-slice', slider)._reverse();
slices.each(function() {
var slice = $(this);
if (i == 0) {
slice.css('top', '0px');
i++;
} else {
slice.css('bottom', '0px');
i = 0;
}
if (v == settings.slices - 1) {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
height : '100%',
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
v++;
});
} else if (settings.effect == 'fold' || vars.randAnim == 'fold') {
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
$('.nivo-slice', slider).each(function() {
var slice = $(this);
var origWidth = slice.width();
slice.css({
top : '0px',
height : '100%',
width : '0px'
});
if (i == settings.slices - 1) {
setTimeout(function() {
slice.animate({
width : origWidth,
opacity : '1.0'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
slice.animate({
width : origWidth,
opacity : '1.0'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
} else if (settings.effect == 'fade' || vars.randAnim == 'fade') {
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height' : '100%',
'width' : slider.width() + 'px'
});
firstSlice.animate({
opacity : '1.0'
}, (settings.animSpeed * 2), '', function() {
slider.trigger('nivo:animFinished');
});
} else if (settings.effect == 'slideInRight' || vars.randAnim == 'slideInRight') {
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height' : '100%',
'width' : '0px',
'opacity' : '1'
});
firstSlice.animate({
width : slider.width() + 'px'
}, (settings.animSpeed * 2), '', function() {
slider.trigger('nivo:animFinished');
});
} else if (settings.effect == 'slideInLeft' || vars.randAnim == 'slideInLeft') {
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height' : '100%',
'width' : '0px',
'opacity' : '1',
'left' : '',
'right' : '0px'
});
firstSlice.animate({
width : slider.width() + 'px'
}, (settings.animSpeed * 2), '', function() {
firstSlice.css({
'left' : '0px',
'right' : ''
});
slider.trigger('nivo:animFinished');
});
} else if (settings.effect == 'boxRandom' || vars.randAnim == 'boxRandom') {
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
var boxes = shuffle($('.nivo-box', slider));
boxes.each(function() {
var box = $(this);
if (i == totalBoxes - 1) {
setTimeout(function() {
box.animate({
opacity : '1'
}, settings.animSpeed, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + timeBuff));
} else {
setTimeout(function() {
box.animate({
opacity : '1'
}, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 20;
i++;
});
} else if (settings.effect == 'boxRain' || vars.randAnim == 'boxRain' || settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' || settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse') {
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
var rowIndex = 0;
var colIndex = 0;
var box2Darr = new Array();
box2Darr[rowIndex] = new Array();
var boxes = $('.nivo-box', slider);
if (settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse') {
boxes = $('.nivo-box', slider)._reverse();
}
boxes.each(function() {
box2Darr[rowIndex][colIndex] = $(this);
colIndex++;
if (colIndex == settings.boxCols) {
rowIndex++;
colIndex = 0;
box2Darr[rowIndex] = new Array();
}
});
for (var cols = 0; cols < (settings.boxCols * 2); cols++) {
var prevCol = cols;
for (var rows = 0; rows < settings.boxRows; rows++) {
if (prevCol >= 0 && prevCol < settings.boxCols) {
(function(row, col, time, i, totalBoxes) {
var box = $(box2Darr[row][col]);
var w = box.width();
var h = box.height();
if (settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse') {
box.width(0).height(0);
}
if (i == totalBoxes - 1) {
setTimeout(function() {
box.animate({
opacity : '1',
width : w,
height : h
}, settings.animSpeed / 1.3, '', function() {
slider.trigger('nivo:animFinished');
});
}, (100 + time));
} else {
setTimeout(function() {
box.animate({
opacity : '1',
width : w,
height : h
}, settings.animSpeed / 1.3);
}, (100 + time));
}
})(rows, prevCol, timeBuff, i, totalBoxes);
i++;
}
prevCol--;
}
timeBuff += 100;
}
}
}
var shuffle = function(arr) {
for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
var trace = function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
}
this.stop = function() {
if (!$(element).data('nivo:vars').stop) {
$(element).data('nivo:vars').stop = true;
trace('Stop Slider');
}
}
this.start = function() {
if ($(element).data('nivo:vars').stop) {
$(element).data('nivo:vars').stop = false;
trace('Start Slider');
}
}
settings.afterLoad.call(this);
return this;
};
$.fn.nivoSlider = function(options) {
return this.each(function(key, value) {
var element = $(this);
if (element.data('nivoslider'))
return element.data('nivoslider');
var nivoslider = new NivoSlider(this, options);
element.data('nivoslider', nivoslider);
});
};
$.fn.nivoSlider.defaults = {
backgroundSize:'',
effect : 'random',
slices : 15,
boxCols : 8,
boxRows : 4,
animSpeed : 500,
pauseTime : 3000,
startSlide : 0,
directionNav : true,
directionNavHide : true,
controlNav : true,
controlNavThumbs : false,
controlNavThumbsFromRel : false,
controlNavThumbsSearch : '.jpg',
controlNavThumbsReplace : '_thumb.jpg',
keyboardNav : true,
pauseOnHover : true,
manualAdvance : false,
captionOpacity : 0.8,
prevText : 'Prev',
nextText : 'Next',
beforeChange : function() {
},
afterChange : function() {
},
slideshowEnd : function() {
},
lastSlide : function() {
},
afterLoad : function() {
}
};
$.fn._reverse = [].reverse;
})(jQuery);
When you initial nivoSlide pass my new parameter backgroundSize:'your width size px your height size px';
Example:
$('#slider').nivoSlider({
backgroundSize:'687px 400px',
effect: 'random',
animSpeed: 500,
pauseTime: 3000,
directionNav: true,
controlNav: true,
controlNavThumbs: false,
pauseOnHover: true});
});

Tumblr get Like Button status with Infinite Scroll

I would like to request the Like Button status of each post (by ID) that is appended by Infinite Scroll.
<li class="post text" id="{PostID}">
The Tumblr Documentation provides this method of checking the status of a Like Button for individual posts:
Tumblr.LikeButton.get_status_by_page(n)
Description: Call this function after requesting a new page of Posts. Takes the page number that was just loaded as an integer.
Finally, here is the Infinite Scroll script (Proto.jp modified by Cody Sherman):
$(document).ready(function() {
var tumblrAutoPager = {
url: "http://proto.jp/",
ver: "0.1.7",
rF: true,
gP: {},
pp: null,
ppId: "",
LN: location.hostname,
init: function() {
if ($("autopagerize_icon") || navigator.userAgent.indexOf('iPhone') != -1) return;
var tAP = tumblrAutoPager;
var p = 1;
var lh = location.href;
var lhp = lh.lastIndexOf("/page/");
var lht = lh.lastIndexOf("/tagged/");
if (lhp != -1) {
p = parseInt(lh.slice(lhp + 6));
tAP.LN = lh.slice(7, lhp);
} else if (lht != -1) {
tAP.LN = lh.slice(7);
if (tAP.LN.slice(tAP.LN.length - 1) == "/") tAP.LN = tAP.LN.slice(0, tAP.LN.length - 1);
} else if ("http://" + tAP.LN + "/" != lh) {
return;
};
var gPFncs = [];
gPFncs[0] = function(aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "autopagerize_page_element") {
r = gCE(aE[i]);
break;
}
}
return r;
};
gPFncs[1] = function(aE) {
var r = [];
for (var i = 0, l = aE.length; i < l; i++) {
var arr = aE[i].className ? aE[i].className.split(" ") : null;
if (arr) {
for (var j = 0; j < arr.length; j++) {
arr[j] == "post" ? r.push(aE[i]) : null;
}
}
}
return r;
};
gPFncs[2] = function(aE) {
var r = [];
var tmpId = tAP.ppId ? [tAP.ppId] : ["posts", "main", "container", "content", "apDiv2", "wrapper", "projects"];
for (var i = 0, l = aE.length; i < l; i++) {
for (var j = 0; j < tmpId.length; j++) {
if (aE[i].id == tmpId[j]) {
r = gCE(aE[i]);
tAP.ppId = aE[i].id;
break;
}
}
}
return r;
};
for (var i = 0; i < gPFncs.length; i++) {
var getElems = gPFncs[i](document.body.getElementsByTagName('*'));
if (getElems.length) {
tAP.gP = gPFncs[i];
tAP.pp = getElems[0].parentNode;
break;
}
}
function gCE(pElem) {
var r = [];
for (var i = 0, l = pElem.childNodes.length; i < l; i++) {
r.push(pElem.childNodes.item(i))
}
return r;
}
if (!tAP.pp) {
return;
}
sendRequest.README = {
license: 'Public Domain',
url: 'http://jsgt.org/lib/ajax/ref.htm',
version: 0.516,
author: 'Toshiro Takahashi'
};
function chkAjaBrowser() {
var A, B = navigator.userAgent;
this.bw = {
safari: ((A = B.split('AppleWebKit/')[1]) ? A.split('(')[0].split('.')[0] : 0) >= 124,
konqueror: ((A = B.split('Konqueror/')[1]) ? A.split(';')[0] : 0) >= 3.3,
mozes: ((A = B.split('Gecko/')[1]) ? A.split(' ')[0] : 0) >= 20011128,
opera: ( !! window.opera) && ((typeof XMLHttpRequest) == 'function'),
msie: ( !! window.ActiveXObject) ? ( !! createHttpRequest()) : false
};
return (this.bw.safari || this.bw.konqueror || this.bw.mozes || this.bw.opera || this.bw.msie)
}
function createHttpRequest() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP')
} catch (B) {
try {
return new ActiveXObject('Microsoft.XMLHTTP')
} catch (A) {
return null
}
}
} else {
return null
}
}
};
function sendRequest(E, R, C, D, F, G, S, A) {
var Q = C.toUpperCase() == 'GET',
H = createHttpRequest();
if (H == null) {
return null
}
if ((G) ? G : false) {
D += ((D.indexOf('?') == -1) ? '?' : '&') + 't=' + (new Date()).getTime()
}
var P = new chkAjaBrowser(),
L = P.bw.opera,
I = P.bw.safari,
N = P.bw.konqueror,
M = P.bw.mozes;
if (typeof E == 'object') {
var J = E.onload;
var O = E.onbeforsetheader
} else {
var J = E;
var O = null
}
if (L || I || M) {
H.onload = function() {
J(H);
H.abort()
}
} else {
H.onreadystatechange = function() {
if (H.readyState == 4) {
J(H);
H.abort()
}
}
}
R = K(R, D);
if (Q) {
D += ((D.indexOf('?') == -1) ? '?' : (R == '') ? '' : '&') + R
}
H.open(C, D, F, S, A);
if ( !! O) {
O(H)
}
B(H);
H.send(R);
function B(T) {
if (!L || typeof T.setRequestHeader == 'function') {
T.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
}
return T
}
function K(X, V) {
var Z = [];
if (typeof X == 'object') {
for (var W in X) {
Y(W, X[W])
}
} else {
if (typeof X == 'string') {
if (X == '') {
return ''
}
if (X.charAt(0) == '&') {
X = X.substring(1, X.length)
}
var T = X.split('&');
for (var W = 0; W < T.length; W++) {
var U = T[W].split('=');
Y(U[0], U[1])
}
}
}
function Y(b, a) {
Z.push(encodeURIComponent(b) + '=' + encodeURIComponent(a))
}
return Z.join('&')
}
return H
}
function addNextPage(oj) {
if (oj.status == 404) {
tAP.remainFlg = false;
return;
}
var d = document.createElement("div");
d.innerHTML = oj.responseText;
var posts = tAP.gP(d.getElementsByTagName("*"));
if (posts.length < 2) {
tAP.rF = false;
return;
}
d = document.createElement("div");
d.className = "tumblrAutoPager_page_info";
tAP.pp.appendChild(d);
for (var i = 0; i < posts.length; i++) {
tAP.pp.appendChild(posts[i]);
}
var footer = $("footer");
footer ? footer.parentNode.appendChild(footer) : null;
tAP.rF = true;
}
watch_scroll();
function watch_scroll() {
var d = document.compatMode == "BackCompat" ? document.body : document.documentElement;
var r = d.scrollHeight - d.clientHeight - (d.scrollTop || document.body.scrollTop);
if (r < d.clientHeight * 2 && tAP.rF) {
tAP.rF = false;
p++;
sendRequest(addNextPage, "", "GET", "http://" + tAP.LN + "/page/" + p, true);
}
setTimeout(arguments.callee, 200);
};
function $(id) {
return document.getElementById(id)
}
},
switchAutoPage: function() {
this.rF = !this.rF;
var aE = document.getElementsByTagName('*');
for (var i = 0, l = aE.length; i < l; i++) {
if (aE[i].className == "tAP_switch") {
aE[i].firstChild.nodeValue = this.rF ? "AutoPage[OFF]" : "AutoPage[ON]";
}
}
}
};
window.addEventListener ? window.addEventListener('load', tumblrAutoPager.init, false) : window.attachEvent ? window.attachEvent("onload", tumblrAutoPager.init) : window.onload = tumblrAutoPager.init;
});
Any insight is greatly appreciated. Thank you!
This seemed to do the trick!
function addNextPage(oj) {
if (oj.status == 404) {
tAP.remainFlg = false;
return;
}
var d = document.createElement("div");
d.innerHTML = oj.responseText;
var posts = tAP.gP(d.getElementsByTagName("*"));
if (posts.length < 2) {
tAP.rF = false;
return;
}
d = document.createElement("div");
d.className = "tumblrAutoPager_page_info";
tAP.pp.appendChild(d);
for (var i = 0; i < posts.length; i++) {
tAP.pp.appendChild(posts[i]);
}
var footer = $("footer");
footer ? footer.parentNode.appendChild(footer) : null;
tAP.rF = true;
//Get Like Button status of newly appended page
Tumblr.LikeButton.get_status_by_page(p);
}

How do I combine all of these scriptmanager scripts?

I ran YSlow on my page and it's complaining I have way too many scripts on my page. On inspection with Firebug I see most of them are of Validation and ScriptManager scripts:
How do I / Can I combine all of these scripts into one? Secondly when I downloaded the contents of WebForms.js it is not minified at all. This is it's content:
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit) {
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options) {
var validationResult = true;
if (options.validation) {
if (typeof(Page_ClientValidate) == 'function') {
validationResult = Page_ClientValidate(options.validationGroup);
}
}
if (validationResult) {
if ((typeof(options.actionUrl) != "undefined") && (options.actionUrl != null) && (options.actionUrl.length > 0)) {
theForm.action = options.actionUrl;
}
if (options.trackFocus) {
var lastFocus = theForm.elements["__LASTFOCUS"];
if ((typeof(lastFocus) != "undefined") && (lastFocus != null)) {
if (typeof(document.activeElement) == "undefined") {
lastFocus.value = options.eventTarget;
}
else {
var active = document.activeElement;
if ((typeof(active) != "undefined") && (active != null)) {
if ((typeof(active.id) != "undefined") && (active.id != null) && (active.id.length > 0)) {
lastFocus.value = active.id;
}
else if (typeof(active.name) != "undefined") {
lastFocus.value = active.name;
}
}
}
}
}
}
if (options.clientSubmit) {
__doPostBack(options.eventTarget, options.eventArgument);
}
}
var __pendingCallbacks = new Array();
var __synchronousCallBackIndex = -1;
function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {
var postData = __theFormPostData +
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
if (theForm["__EVENTVALIDATION"]) {
postData += "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
}
var xmlRequest,e;
try {
xmlRequest = new XMLHttpRequest();
}
catch(e) {
try {
xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
}
}
var setRequestHeaderMethodExists = true;
try {
setRequestHeaderMethodExists = (xmlRequest && xmlRequest.setRequestHeader);
}
catch(e) {}
var callback = new Object();
callback.eventCallback = eventCallback;
callback.context = context;
callback.errorCallback = errorCallback;
callback.async = useAsync;
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
if (!useAsync) {
if (__synchronousCallBackIndex != -1) {
__pendingCallbacks[__synchronousCallBackIndex] = null;
}
__synchronousCallBackIndex = callbackIndex;
}
if (setRequestHeaderMethodExists) {
xmlRequest.onreadystatechange = WebForm_CallbackComplete;
callback.xmlRequest = xmlRequest;
// e.g. http:
var action = theForm.action || document.location.pathname, fragmentIndex = action.indexOf('#');
if (fragmentIndex !== -1) {
action = action.substr(0, fragmentIndex);
}
if (!__nonMSDOMBrowser) {
var queryIndex = action.indexOf('?');
if (queryIndex !== -1) {
var path = action.substr(0, queryIndex);
if (path.indexOf("%") === -1) {
action = encodeURI(path) + action.substr(queryIndex);
}
}
else if (action.indexOf("%") === -1) {
action = encodeURI(action);
}
}
xmlRequest.open("POST", action, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xmlRequest.send(postData);
return;
}
callback.xmlRequest = new Object();
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
var xmlRequestFrame = document.frames[callbackFrameID];
if (!xmlRequestFrame) {
xmlRequestFrame = document.createElement("IFRAME");
xmlRequestFrame.width = "1";
xmlRequestFrame.height = "1";
xmlRequestFrame.frameBorder = "0";
xmlRequestFrame.id = callbackFrameID;
xmlRequestFrame.name = callbackFrameID;
xmlRequestFrame.style.position = "absolute";
xmlRequestFrame.style.top = "-100px"
xmlRequestFrame.style.left = "-100px";
try {
if (callBackFrameUrl) {
xmlRequestFrame.src = callBackFrameUrl;
}
}
catch(e) {}
document.body.appendChild(xmlRequestFrame);
}
var interval = window.setInterval(function() {
xmlRequestFrame = document.frames[callbackFrameID];
if (xmlRequestFrame && xmlRequestFrame.document) {
window.clearInterval(interval);
xmlRequestFrame.document.write("");
xmlRequestFrame.document.close();
xmlRequestFrame.document.write('<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
xmlRequestFrame.document.close();
xmlRequestFrame.document.forms[0].action = theForm.action;
var count = __theFormPostCollection.length;
var element;
for (var i = 0; i < count; i++) {
element = __theFormPostCollection[i];
if (element) {
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
fieldElement.type = "hidden";
fieldElement.name = element.name;
fieldElement.value = element.value;
xmlRequestFrame.document.forms[0].appendChild(fieldElement);
}
}
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIdFieldElement.type = "hidden";
callbackIdFieldElement.name = "__CALLBACKID";
callbackIdFieldElement.value = eventTarget;
xmlRequestFrame.document.forms[0].appendChild(callbackIdFieldElement);
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackParamFieldElement.type = "hidden";
callbackParamFieldElement.name = "__CALLBACKPARAM";
callbackParamFieldElement.value = eventArgument;
xmlRequestFrame.document.forms[0].appendChild(callbackParamFieldElement);
if (theForm["__EVENTVALIDATION"]) {
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackValidationFieldElement.type = "hidden";
callbackValidationFieldElement.name = "__EVENTVALIDATION";
callbackValidationFieldElement.value = theForm["__EVENTVALIDATION"].value;
xmlRequestFrame.document.forms[0].appendChild(callbackValidationFieldElement);
}
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
callbackIndexFieldElement.type = "hidden";
callbackIndexFieldElement.name = "__CALLBACKINDEX";
callbackIndexFieldElement.value = callbackIndex;
xmlRequestFrame.document.forms[0].appendChild(callbackIndexFieldElement);
xmlRequestFrame.document.forms[0].submit();
}
}, 10);
}
function WebForm_CallbackComplete() {
for (var i = 0; i < __pendingCallbacks.length; i++) {
callbackObject = __pendingCallbacks[i];
if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
if (!__pendingCallbacks[i].async) {
__synchronousCallBackIndex = -1;
}
__pendingCallbacks[i] = null;
var callbackFrameID = "__CALLBACKFRAME" + i;
var xmlRequestFrame = document.getElementById(callbackFrameID);
if (xmlRequestFrame) {
xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
}
WebForm_ExecuteCallback(callbackObject);
}
}
}
function WebForm_ExecuteCallback(callbackObject) {
var response = callbackObject.xmlRequest.responseText;
if (response.charAt(0) == "s") {
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(1), callbackObject.context);
}
}
else if (response.charAt(0) == "e") {
if ((typeof(callbackObject.errorCallback) != "undefined") && (callbackObject.errorCallback != null)) {
callbackObject.errorCallback(response.substring(1), callbackObject.context);
}
}
else {
var separatorIndex = response.indexOf("|");
if (separatorIndex != -1) {
var validationFieldLength = parseInt(response.substring(0, separatorIndex));
if (!isNaN(validationFieldLength)) {
var validationField = response.substring(separatorIndex + 1, separatorIndex + validationFieldLength + 1);
if (validationField != "") {
var validationFieldElement = theForm["__EVENTVALIDATION"];
if (!validationFieldElement) {
validationFieldElement = document.createElement("INPUT");
validationFieldElement.type = "hidden";
validationFieldElement.name = "__EVENTVALIDATION";
theForm.appendChild(validationFieldElement);
}
validationFieldElement.value = validationField;
}
if ((typeof(callbackObject.eventCallback) != "undefined") && (callbackObject.eventCallback != null)) {
callbackObject.eventCallback(response.substring(separatorIndex + validationFieldLength + 1), callbackObject.context);
}
}
}
}
}
function WebForm_FillFirstAvailableSlot(array, element) {
var i;
for (i = 0; i < array.length; i++) {
if (!array[i]) break;
}
array[i] = element;
return i;
}
var __nonMSDOMBrowser = (window.navigator.appName.toLowerCase().indexOf('explorer') == -1);
var __theFormPostData = "";
var __theFormPostCollection = new Array();
function WebForm_InitCallback() {
var count = theForm.elements.length;
var element;
for (var i = 0; i < count; i++) {
element = theForm.elements[i];
var tagName = element.tagName.toLowerCase();
if (tagName == "input") {
var type = element.type;
if ((type == "text" || type == "hidden" || type == "password" ||
((type == "checkbox" || type == "radio") && element.checked)) &&
(element.id != "__EVENTVALIDATION")) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
else if (tagName == "select") {
var selectCount = element.options.length;
for (var j = 0; j < selectCount; j++) {
var selectChild = element.options[j];
if (selectChild.selected == true) {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
else if (tagName == "textarea") {
WebForm_InitCallbackAddField(element.name, element.value);
}
}
}
function WebForm_InitCallbackAddField(name, value) {
var nameValue = new Object();
nameValue.name = name;
nameValue.value = value;
__theFormPostCollection[__theFormPostCollection.length] = nameValue;
__theFormPostData += WebForm_EncodeCallback(name) + "=" + WebForm_EncodeCallback(value) + "&";
}
function WebForm_EncodeCallback(parameter) {
if (encodeURIComponent) {
return encodeURIComponent(parameter);
}
else {
return escape(parameter);
}
}
var __disabledControlArray = new Array();
function WebForm_ReEnableControls() {
if (typeof(__enabledControlArray) == 'undefined') {
return false;
}
var disabledIndex = 0;
for (var i = 0; i < __enabledControlArray.length; i++) {
var c;
if (__nonMSDOMBrowser) {
c = document.getElementById(__enabledControlArray[i]);
}
else {
c = document.all[__enabledControlArray[i]];
}
if ((typeof(c) != "undefined") && (c != null) && (c.disabled == true)) {
c.disabled = false;
__disabledControlArray[disabledIndex++] = c;
}
}
setTimeout("WebForm_ReDisableControls()", 0);
return true;
}
function WebForm_ReDisableControls() {
for (var i = 0; i < __disabledControlArray.length; i++) {
__disabledControlArray[i].disabled = true;
}
}
function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (src &&
((src.tagName.toLowerCase() == "input") &&
(src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")) ||
((src.tagName.toLowerCase() == "a") &&
(src.href != null) && (src.href != "")) ||
(src.tagName.toLowerCase() == "textarea")) {
return true;
}
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof(defaultButton.click) != "undefined") {
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
return true;
}
function WebForm_GetScrollX() {
if (__nonMSDOMBrowser) {
return window.pageXOffset;
}
else {
if (document.documentElement && document.documentElement.scrollLeft) {
return document.documentElement.scrollLeft;
}
else if (document.body) {
return document.body.scrollLeft;
}
}
return 0;
}
function WebForm_GetScrollY() {
if (__nonMSDOMBrowser) {
return window.pageYOffset;
}
else {
if (document.documentElement && document.documentElement.scrollTop) {
return document.documentElement.scrollTop;
}
else if (document.body) {
return document.body.scrollTop;
}
}
return 0;
}
function WebForm_SaveScrollPositionSubmit() {
if (__nonMSDOMBrowser) {
theForm.elements['__SCROLLPOSITIONY'].value = window.pageYOffset;
theForm.elements['__SCROLLPOSITIONX'].value = window.pageXOffset;
}
else {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
}
if ((typeof(this.oldSubmit) != "undefined") && (this.oldSubmit != null)) {
return this.oldSubmit();
}
return true;
}
function WebForm_SaveScrollPositionOnSubmit() {
theForm.__SCROLLPOSITIONX.value = WebForm_GetScrollX();
theForm.__SCROLLPOSITIONY.value = WebForm_GetScrollY();
if ((typeof(this.oldOnSubmit) != "undefined") && (this.oldOnSubmit != null)) {
return this.oldOnSubmit();
}
return true;
}
function WebForm_RestoreScrollPosition() {
if (__nonMSDOMBrowser) {
window.scrollTo(theForm.elements['__SCROLLPOSITIONX'].value, theForm.elements['__SCROLLPOSITIONY'].value);
}
else {
window.scrollTo(theForm.__SCROLLPOSITIONX.value, theForm.__SCROLLPOSITIONY.value);
}
if ((typeof(theForm.oldOnLoad) != "undefined") && (theForm.oldOnLoad != null)) {
return theForm.oldOnLoad();
}
return true;
}
function WebForm_TextBoxKeyHandler(event) {
if (event.keyCode == 13) {
var target;
if (__nonMSDOMBrowser) {
target = event.target;
}
else {
target = event.srcElement;
}
if ((typeof(target) != "undefined") && (target != null)) {
if (typeof(target.onchange) != "undefined") {
target.onchange();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}
function WebForm_TrimString(value) {
return value.replace(/^\s+|\s+$/g, '')
}
function WebForm_AppendToClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index === -1) {
element.className = (element.className === '') ? className : element.className + ' ' + className;
}
}
function WebForm_RemoveClassName(element, className) {
var currentClassName = ' ' + WebForm_TrimString(element.className) + ' ';
className = WebForm_TrimString(className);
var index = currentClassName.indexOf(' ' + className + ' ');
if (index >= 0) {
element.className = WebForm_TrimString(currentClassName.substring(0, index) + ' ' +
currentClassName.substring(index + className.length + 1, currentClassName.length));
}
}
function WebForm_GetElementById(elementId) {
if (document.getElementById) {
return document.getElementById(elementId);
}
else if (document.all) {
return document.all[elementId];
}
else return null;
}
function WebForm_GetElementByTagName(element, tagName) {
var elements = WebForm_GetElementsByTagName(element, tagName);
if (elements && elements.length > 0) {
return elements[0];
}
else return null;
}
function WebForm_GetElementsByTagName(element, tagName) {
if (element && tagName) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(tagName);
}
if (element.all && element.all.tags) {
return element.all.tags(tagName);
}
}
return null;
}
function WebForm_GetElementDir(element) {
if (element) {
if (element.dir) {
return element.dir;
}
return WebForm_GetElementDir(element.parentNode);
}
return "ltr";
}
function WebForm_GetElementPosition(element) {
var result = new Object();
result.x = 0;
result.y = 0;
result.width = 0;
result.height = 0;
if (element.offsetParent) {
result.x = element.offsetLeft;
result.y = element.offsetTop;
var parent = element.offsetParent;
while (parent) {
result.x += parent.offsetLeft;
result.y += parent.offsetTop;
var parentTagName = parent.tagName.toLowerCase();
if (parentTagName != "table" &&
parentTagName != "body" &&
parentTagName != "html" &&
parentTagName != "div" &&
parent.clientTop &&
parent.clientLeft) {
result.x += parent.clientLeft;
result.y += parent.clientTop;
}
parent = parent.offsetParent;
}
}
else if (element.left && element.top) {
result.x = element.left;
result.y = element.top;
}
else {
if (element.x) {
result.x = element.x;
}
if (element.y) {
result.y = element.y;
}
}
if (element.offsetWidth && element.offsetHeight) {
result.width = element.offsetWidth;
result.height = element.offsetHeight;
}
else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
result.width = element.style.pixelWidth;
result.height = element.style.pixelHeight;
}
return result;
}
function WebForm_GetParentByTagName(element, tagName) {
var parent = element.parentNode;
var upperTagName = tagName.toUpperCase();
while (parent && (parent.tagName.toUpperCase() != upperTagName)) {
parent = parent.parentNode ? parent.parentNode : parent.parentElement;
}
return parent;
}
function WebForm_SetElementHeight(element, height) {
if (element && element.style) {
element.style.height = height + "px";
}
}
function WebForm_SetElementWidth(element, width) {
if (element && element.style) {
element.style.width = width + "px";
}
}
function WebForm_SetElementX(element, x) {
if (element && element.style) {
element.style.left = x + "px";
}
}
function WebForm_SetElementY(element, y) {
if (element && element.style) {
element.style.top = y + "px";
}
}
How do I do minification of this script?
Have a look at this project that uses a .NET port of YUI script and css compressor. We utilized something similar in one of the projects I worked on and it turned out great. Make sure to verify your JavaScript with JSLint or something similar before minimizing it as something very minor may screw things up (like missing a closing semicolon for example).

Resources