Multiday Calendar Datepicker JQuery Plugin - javascript

I'm using jQuery plugin from these websites web , github.
This is screenshot whith my problem:
For some reason some months are not full ie. last day in month transfer in next month. Why?
This is JavaScript:
(function($) {
$.fn.jCal = function(opt) {
$.jCal(this, opt);
};
$.jCal = function(target, opt) {
opt = $.extend({
day : new Date(),
days : 1,
showMonths : 1,
monthSelect : false,
dCheck : function(day) {
return true;
},
callback : function(day, days) {
return true;
},
selectedBG : 'rgb(0, 143, 214)',
defaultBG : 'rgb(255, 255, 255)',
dayOffset : 0,
forceWeek : false,
dow : [ 'S', 'M', 'T', 'W', 'T', 'F', 'S' ],
ml : [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
ms : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
_target : target
}, opt);
opt.day = new Date(opt.day.getFullYear(), opt.day.getMonth(), 1);
if (!$(opt._target).data('days')) $(opt._target).data('days', opt.days);
$(target).stop().empty();
for (var sm = 0; sm < opt.showMonths; sm++) $(target).append('<div class="jCalMo"></div>');
opt.cID = 'c' + $('.jCalMo').length;$('.jCalMo', target).each(function(ind) {
drawCalControl($(this), $.extend({}, opt, {
'ind' : ind,
'day' : new Date(new Date(opt.day.getTime()).setMonth(new Date(opt.day.getTime()).getMonth() + ind))
}));drawCal($(this), $.extend({}, opt, {
'ind' : ind,
'day' : new Date(new Date(opt.day.getTime()).setMonth(new Date(opt.day.getTime()).getMonth() + ind))
}));
});
if ($(opt._target).data('day') && $(opt._target).data('days')) reSelectDates(target, $(opt._target).data('day'), $(opt._target).data('days'), opt);
};
function drawCalControl(target, opt) {
$(target).append('<div class="jCal">' + ((opt.ind == 0) ? '<div class="left" />' : '') + '<div class="month">' + '<span class="monthYear">' + opt.day.getFullYear() + '</span>' + '<span class="monthName">' + opt.ml[opt.day.getMonth()] + '</span>' + '</div>' + ((opt.ind == (opt.showMonths - 1)) ? '<div class="right" />' : '') + '</div>');
if (opt.monthSelect) $(target).find('.jCal .monthName, .jCal .monthYear').bind('mouseover', $.extend({}, opt), function(e) {
$(this).removeClass('monthYearHover').removeClass('monthNameHover');
if ($('.jCalMask', e.data._target).length == 0) $(this).addClass($(this).attr('class') + 'Hover');
}).bind('mouseout', function() {
$(this).removeClass('monthYearHover').removeClass('monthNameHover');
}).bind('click', $.extend({}, opt), function(e) {
$('.jCalMo .monthSelector, .jCalMo .monthSelectorShadow').remove();
var monthName = $(this).hasClass('monthName'),
pad = Math.max(parseInt($(this).css('padding-left')), parseInt($(this).css('padding-left'))) || 2,
calcTop = (($(this).offset()).top - ((monthName ? e.data.day.getMonth() : 2) * ($(this).height() + 0)));
calcTop = calcTop > 0 ? calcTop : 0;
var topDiff = ($(this).offset()).top - calcTop;
$('<div class="monthSelectorShadow" style="' + 'top:' + $(e.data._target).offset().top + 'px; ' + 'left:' + $(e.data._target).offset().left + 'px; ' + 'width:' + ($(e.data._target).width() + (parseInt($(e.data._target).css('paddingLeft')) || 0) + (parseInt($(e.data._target).css('paddingRight')) || 0)) + 'px; ' + 'height:' + ($(e.data._target).height() + (parseInt($(e.data._target).css('paddingTop')) || 0) + (parseInt($(e.data._target).css('paddingBottom')) || 0)) + 'px;">' + '</div>').css('opacity', 0.01).appendTo($(this).parent());$('<div class="monthSelector" style="' + 'top:' + calcTop + 'px; ' + 'left:' + (($(this).offset()).left) + 'px; ' + 'width:' + ($(this).width() + (pad * 2)) + 'px;">' + '</div>').css('opacity', 0).appendTo($(this).parent());
for (var di = (monthName ? 0 : -2), dd = (monthName ? 12 : 3); di < dd; di++) $(this).clone().removeClass('monthYearHover').removeClass('monthNameHover').addClass('monthSelect').attr('id', monthName ? (di + 1) + '_1_' + e.data.day.getFullYear() : (e.data.day.getMonth() + 1) + '_1_' + (e.data.day.getFullYear() + di)).html(monthName ? e.data.ml[di] : (e.data.day.getFullYear() + di)).css('top', ($(this).height() * di)).appendTo($(this).parent().find('.monthSelector'));
var moSel = $(this).parent().find('.monthSelector').get(0),
diffOff = $(moSel).height() - ($(moSel).height() - topDiff);
$(moSel).css('clip', 'rect(' + diffOff + 'px ' + ($(this).width() + (pad * 2)) + 'px ' + diffOff + 'px 0px)').animate({
'opacity' : .92,
'clip' : 'rect(0px ' + ($(this).width() + (pad * 2)) + 'px ' + $(moSel).height() + 'px 0px)'
}, 'fast', function() {
$(this).parent().find('.monthSelectorShadow').bind('mouseover click', function() {
$(this).parent().find('.monthSelector').remove();$(this).remove();
});
}).parent().find('.monthSelectorShadow').animate({
'opacity' : .1
}, 'fast');$('.jCalMo .monthSelect', e.data._target).bind('mouseover mouseout click', $.extend({}, e.data), function(e) {
if (e.type == 'click') $(e.data._target).jCal($.extend(e.data, {
day : new Date($(this).attr('id').replace(/_/g, '/'))
}));else
$(this).toggleClass('monthSelectHover');
});
});
$(target).find('.jCal .left').bind('click', $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var mD = {
w : 0,
h : 0
};
$('.jCalMo', e.data._target).each(function() {
mD.w += $(this).width() + parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
var cH = $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
mD.h = ((cH > mD.h) ? cH : mD.h);
});$(e.data._target).prepend('<div class="jCalMo"></div>');
e.data.day = new Date($('div[id*=' + e.data.cID + 'd_]:first', e.data._target).attr('id').replace(e.data.cID + 'd_', '').replace(/_/g, '/'));e.data.day.setDate(1);e.data.day.setMonth(e.data.day.getMonth() - 1);drawCalControl($('.jCalMo:first', e.data._target), e.data);drawCal($('.jCalMo:first', e.data._target), e.data);
if (e.data.showMonths > 1) {
$('.right', e.data._target).clone(true).appendTo($('.jCalMo:eq(' + (e.data.showMonths - 1) + ') .jCal', e.data._target));$('.left:last, .right:last', e.data._target).remove();
}
$(e.data._target).append('<div class="jCalSpace" style="width:' + mD.w + 'px; height:' + mD.h + 'px;"></div>');$('.jCalMo', e.data._target).wrapAll('<div class="jCalMask" style="clip:rect(0px ' + mD.w + 'px ' + mD.h + 'px 0px); width:' + (mD.w + (mD.w / e.data.showMonths)) + 'px; height:' + mD.h + 'px;">' + '<div class="jCalMove"></div>' + '</div>');$('.jCalMove', e.data._target).css('margin-left', ((mD.w / e.data.showMonths) * -1) + 'px').css('opacity', 0.5).animate({
marginLeft : '0px'
}, 'fast', function() {
$(this).children('.jCalMo:not(:last)').appendTo($(e.data._target));$('.jCalSpace, .jCalMask', e.data._target).empty().remove();
if ($(e.data._target).data('day')) reSelectDates(e.data._target, $(e.data._target).data('day'), $(e.data._target).data('days'), e.data);
});
});$(target).find('.jCal .right').bind('click', $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var mD = {
w : 0,
h : 0
};
$('.jCalMo', e.data._target).each(function() {
mD.w += $(this).width() + parseInt($(this).css('padding-left')) + parseInt($(this).css('padding-right'));
var cH = $(this).height() + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'));
mD.h = ((cH > mD.h) ? cH : mD.h);
});$(e.data._target).append('<div class="jCalMo"></div>');
e.data.day = new Date($('div[id^=' + e.data.cID + 'd_]:last', e.data._target).attr('id').replace(e.data.cID + 'd_', '').replace(/_/g, '/'));e.data.day.setDate(1);e.data.day.setMonth(e.data.day.getMonth() + 1);drawCalControl($('.jCalMo:last', e.data._target), e.data);drawCal($('.jCalMo:last', e.data._target), e.data);
if (e.data.showMonths > 1) {
$('.left', e.data._target).clone(true).prependTo($('.jCalMo:eq(1) .jCal', e.data._target));$('.left:first, .right:first', e.data._target).remove();
}
$(e.data._target).append('<div class="jCalSpace" style="width:' + mD.w + 'px; height:' + mD.h + 'px;"></div>');$('.jCalMo', e.data._target).wrapAll('<div class="jCalMask" style="clip:rect(0px ' + mD.w + 'px ' + mD.h + 'px 0px); width:' + (mD.w + (mD.w / e.data.showMonths)) + 'px; height:' + mD.h + 'px;">' + '<div class="jCalMove"></div>' + '</div>');$('.jCalMove', e.data._target).css('opacity', 0.5).animate({
marginLeft : ((mD.w / e.data.showMonths) * -1) + 'px'
}, 'fast', function() {
$(this).children('.jCalMo:not(:first)').appendTo($(e.data._target));$('.jCalSpace, .jCalMask', e.data._target).empty().remove();
if ($(e.data._target).data('day')) reSelectDates(e.data._target, $(e.data._target).data('day'), $(e.data._target).data('days'), e.data);
$(this).children('.jCalMo:not(:first)').removeClass('');
});
});$('.jCal', target).each(function() {
var width = $(this).parent().width() - ($('.left', this).width() || 0) - ($('.right', this).width() || 0);
$('.month', this).css('width', width).find('.monthName, .monthYear').css('width', ((width / 2) - 4));
});$(window).load(function() {
$('.jCal', target).each(function() {
var width = $(this).parent().width() - ($('.left', this).width() || 0) - ($('.right', this).width() || 0);
$('.month', this).css('width', width).find('.monthName, .monthYear').css('width', ((width / 2) - 4));
});
});
}
;
function reSelectDates(target, day, days, opt) {
var fDay = new Date(day.getTime());
var sDay = new Date(day.getTime());
for (var fC = false, di = 0, dC = days; di < dC; di++) {
var dF = $(target).find('div[id*=d_' + (sDay.getMonth() + 1) + '_' + sDay.getDate() + '_' + sDay.getFullYear() + ']');
if (dF.length > 0) {
dF.stop().addClass('selectedDay');
fC = true;
}
sDay.setDate(sDay.getDate() + 1);
}
if (fC && typeof opt.callback == 'function') opt.callback(day, days);
}
;
function drawCal(target, opt) {
for (var ds = 0, length = opt.dow.length; ds < length; ds++) {
$(target).append('<div class="dow">' + opt.dow[ds] + '</div>');
}
var fd = new Date(new Date(opt.day.getTime()).setDate(1));
var ldlm = new Date(new Date(fd.getTime()).setDate(0));
var ld = new Date(new Date(new Date(fd.getTime()).setMonth(fd.getMonth() + 1)).setDate(0));
var copt = {
fd : fd.getDay(),
lld : ldlm.getDate(),
ld : ld.getDate()
};
var offsetDayStart = ((copt.fd < opt.dayOffset) ? (opt.dayOffset - 7) : 1);
var offsetDayEnd = ((ld.getDay() < opt.dayOffset) ? (7 - ld.getDay()) : ld.getDay());
for (var d = offsetDayStart, dE = (copt.fd + copt.ld + (7 - offsetDayEnd)); d < dE; d++) $(target).append(((d <= (copt.fd - opt.dayOffset)) ? '<div id="' + opt.cID + 'd' + d + '" class="pday">' + (copt.lld - ((copt.fd - opt.dayOffset) - d)) + '</div>' : ((d > ((copt.fd - opt.dayOffset) + copt.ld)) ? '<div id="' + opt.cID + 'd' + d + '" class="aday">' + (d - ((copt.fd - opt.dayOffset) + copt.ld)) + '</div>' : '<div id="' + opt.cID + 'd_' + (fd.getMonth() + 1) + '_' + (d - (copt.fd - opt.dayOffset)) + '_' + fd.getFullYear() + '" class="' + ((opt.dCheck(new Date((new Date(fd.getTime())).setDate(d - (copt.fd - opt.dayOffset))))) ? 'day' : 'invday') + '">' + (d - (copt.fd - opt.dayOffset)) + '</div>')));
$(target).find('div[id^=' + opt.cID + 'd]:first, div[id^=' + opt.cID + 'd]:nth-child(7n+2)').before('<br style="clear:both; font-size:0.1em;" />');$(target).find('div[id^=' + opt.cID + 'd_]:not(.invday)').bind("mouseover mouseout click", $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var osDate = new Date($(this).attr('id').replace(/c[0-9]{1,}d_([0-9]{1,2})_([0-9]{1,2})_([0-9]{4})/, '$1/$2/$3'));
if (e.data.forceWeek) osDate.setDate(osDate.getDate() + (e.data.dayOffset - osDate.getDay()));
var sDate = new Date(osDate.getTime());
if (e.type == 'click') $('div[id*=d_]', e.data._target).stop().removeClass('selectedDay').removeClass('overDay').css('backgroundColor', '');
for (var di = 0, ds = $(e.data._target).data('days'); di < ds; di++) {
var currDay = $(e.data._target).find('#' + e.data.cID + 'd_' + (sDate.getMonth() + 1) + '_' + sDate.getDate() + '_' + sDate.getFullYear());
if (currDay.length == 0 || $(currDay).hasClass('invday')) break;
if (e.type == 'mouseover') $(currDay).addClass('overDay');
else if (e.type == 'mouseout') $(currDay).stop().removeClass('overDay').css('backgroundColor', '');
else if (e.type == 'click') $(currDay).stop().addClass('selectedDay');
sDate.setDate(sDate.getDate() + 1);
}
if (e.type == 'click') {
e.data.day = osDate;e.data.callback(osDate, di);
di = ds;$(e.data._target).data('day', e.data.day).data('days', di);
}
});
};})(jQuery);
And code in html:
<script language="JavaScript" type="text/javascript" src="${contextPath}include/js/jCal.min.js"></script>
<script language="javascript">
var calSettings = {
1:{calDay: 0, names: ['S','M','T','W','T','F','S']}, //sunday
2:{calDay: 1, names: ['M','T','W','T','F','S','S']}, //monday
3:{calDay: -5, names: ['T','W','T','F','S','S','M']}, //tuesday
4:{calDay: -4, names: ['W','T','F','S','S','M','T']}, //wednesday
5:{calDay: -3, names: ['T','F','S','S','M','T','W']}, //thursday
6:{calDay: -2, names: ['F','S','S','M','T','W','T']}, //friday
7:{calDay: -1, names: ['S','S','M','T','W','T','F']}}; //saturday
busyDays= new Array($busyDays);
calendarMaxDateTime = $calendarMaxDate.getTime();
jQuery(document).ready(function () {
$('#calOne').jCal({
day: new Date($calendarSetDate.getTime()),
days: 7,
showMonths: 5,
monthSelect: true,
forceWeek: true, // force full week selection
dow: calSettings[${defaultCheckinDay}].names,
callback: function (day, days) {
if(days==7){//disabling selection of periods shorter than 7 days
document.getElementById('bookingForm1')["filter_date"].value=day.getDate();
document.getElementById('bookingForm1')["filter_month"].value=day.getMonth();
document.getElementById('bookingForm1')["filter_year"].value=day.getFullYear();
document.getElementById('bookingForm1').submit();
return true;
}
}
});
});
</script>
I dont know where is problem, i looking in this script few hours i cant detect bug. Plz help.

I changes two line of code in this function in JavaScript and now works:
function drawCal(target, opt) {
for (var ds = 0, length = opt.dow.length; ds < length; ds++) $(target).append('<div class="dow">' + opt.dow[ds] + '</div>');
var fd = new Date(new Date(opt.day.getTime()).setDate(1));
var ldlm = new Date(new Date(fd.getTime()).setDate(0));
var ld = new Date(new Date(new Date(fd.getTime()).setMonth(fd.getMonth() + 1)).setDate(0));
var copt = {
fd : fd.getDay(),
lld : ldlm.getDate(),
ld : ld.getDate()
};
var offsetDayStart = ((copt.fd < opt.dayOffset) ? (opt.dayOffset - 7) : 1);
var offsetDayEnd = ((ld.getDay() < opt.dayOffset) ? (7 - ld.getDay()) : ld.getDay());
if(offsetDayEnd == 6) offsetDayEnd = 5;
for (var d = offsetDayStart, dE = (copt.fd + copt.ld + (7 - offsetDayEnd)); d < dE; d++) $(target).append(((d <= (copt.fd - opt.dayOffset)) ? '<div id="' + opt.cID + 'd' + d + '" class="pday">' + (copt.lld - ((copt.fd - opt.dayOffset) - d)) + '</div>' : ((d > ((copt.fd - opt.dayOffset) + copt.ld)) ? '<div id="' + opt.cID + 'd' + d + '" class="aday">' + (d - ((copt.fd - opt.dayOffset) + copt.ld)) + '</div>' : '<div id="' + opt.cID + 'd_' + (fd.getMonth() + 1) + '_' + (d - (copt.fd - opt.dayOffset)) + '_' + fd.getFullYear() + '" class="' + ((opt.dCheck(new Date((new Date(fd.getTime())).setDate(d - (copt.fd - opt.dayOffset))))) ? 'day' : 'invday') + '">' + (d - (copt.fd - opt.dayOffset)) + '</div>')));
$(target).find('div[id^=' + opt.cID + 'd]:first, div[id^=' + opt.cID + 'd]:nth-child(7n+2)').before('<br style="clear:both; font-size:0.1em;" />');$(target).find('div[id^=' + opt.cID + 'd_]:not(.invday)').bind("mouseover mouseout click", $.extend({}, opt), function(e) {
if ($('.jCalMask', e.data._target).length > 0) return false;
var osDate = new Date($(this).attr('id').replace(/c[0-9]{1,}d_([0-9]{1,2})_([0-9]{1,2})_([0-9]{4})/, '$1/$2/$3'));
osDate.setDate(osDate.getDate() + 1);
if (e.data.forceWeek) osDate.setDate(osDate.getDate() + (e.data.dayOffset - osDate.getDay()));
var sDate = new Date(osDate.getTime());
if (e.type == 'click') $('div[id*=d_]', e.data._target).stop().removeClass('selectedDay').removeClass('overDay').css('backgroundColor', '');
for (var di = 0, ds = $(e.data._target).data('days'); di < ds; di++) {
var currDay = $(e.data._target).find('#' + e.data.cID + 'd_' + (sDate.getMonth() + 1) + '_' + sDate.getDate() + '_' + sDate.getFullYear());
if (currDay.length == 0 || $(currDay).hasClass('invday')) break;
if (e.type == 'mouseover') $(currDay).addClass('overDay');
else if (e.type == 'mouseout') $(currDay).stop().removeClass('overDay').css('backgroundColor', '');
else if (e.type == 'click') $(currDay).stop().addClass('selectedDay');
sDate.setDate(sDate.getDate() + 1);
}
if (e.type == 'click') {
e.data.day = osDate;e.data.callback(osDate, di);
di = ds;$(e.data._target).data('day', e.data.day).data('days', di);
}
});
}

Related

I am trying to create a battle ship game and can not figure out a bug that appeared

I am trying to create a battle ship game.
But I encountered a bug. I wrote some code that should (at least what I thought) create 2 boats, 1 5 blocks long and 1 4 blocks long.
I want to create the game in a table, with each td representing one block of the boat.
The bug is: when I load the page, sometimes the boat with 4 blocks appears more than once. I tried staring at the code for hours and debug it, but I'm quite new to coding and couldn't figure it out.
<!DOCTYPE html>
<html>
<head>
<title>Battle Ships</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
th, td {
width: 32px;
height: 32px;
background-color: grey;
}
.boat {
width: 32px;
height: 32px;
background-color: red;
}
</style>
<script>
$(document).ready(function(){
for (var vr = 0; vr < 11; vr++) {
var vrsta = document.getElementById('tabela').insertRow(vr);
for (var st = 0; st < 11; st++) {
var okvir = vrsta.insertCell(st);
okvir.id = "x=" + st + "&y=" + vr;
okvir.setAttribute("onclick", "koord(this.id)");
//okvir.setAttribute("class", "okvir");
okvir.innerHTML = "x-" + st + " y-" + vr;
}
}
});
function generateBoats() {
console.log("func");
$("tr").children().removeClass("boat");
generateBoat5();
generateBoat4();
}
function generateBoat5() {
// boat 5
var rotation = Math.floor((Math.random() * 2));
var randX = Math.floor((Math.random() * 11));
var randY = Math.floor((Math.random() * 11));
var generiranID = "5___x=" + randX + "&y=" + randY;
console.log(generiranID);
console.log(rotation);
if (rotation == 0) {
if (randX < 7) {
var nID = "x=" + randX + "&y=" + randY;
var nID2 = "x=" + (randX + 1) + "&y=" + randY;
var nID3 = "x=" + (randX + 2) + "&y=" + randY;
var nID4 = "x=" + (randX + 3) + "&y=" + randY;
var nID5 = "x=" + (randX + 4) + "&y=" + randY;
//console.log(nID5);
$(document.getElementById(nID)).addClass("boat");
$(document.getElementById(nID2)).addClass("boat");
$(document.getElementById(nID3)).addClass("boat");
$(document.getElementById(nID4)).addClass("boat");
$(document.getElementById(nID5)).addClass("boat");
}
else {
generateBoats();
}
}
else if (rotation == 1) {
if (randY < 7) {
var nID = "x=" + randX + "&y=" + randY;
var nID2 = "x=" + randX + "&y=" + (randY + 1);
var nID3 = "x=" + randX + "&y=" + (randY + 2);
var nID4 = "x=" + randX + "&y=" + (randY + 3);
var nID5 = "x=" + randX + "&y=" + (randY + 4);
//console.log(nID5);
$(document.getElementById(nID)).addClass("boat");
$(document.getElementById(nID2)).addClass("boat");
$(document.getElementById(nID3)).addClass("boat");
$(document.getElementById(nID4)).addClass("boat");
$(document.getElementById(nID5)).addClass("boat");
}
else {
generateBoats();
}
}
}
function generateBoat4() {
//boat 4
var rotation = Math.floor((Math.random() * 2));
var randX = Math.floor((Math.random() * 11));
var randY = Math.floor((Math.random() * 11));
var generiranID = "4___x=" + randX + "&y=" + randY;
console.log(generiranID);
console.log(rotation);
if (rotation == 0) {
if (randX < 8) {
var nID = "x=" + randX + "&y=" + randY;
var nID2 = "x=" + (randX + 1) + "&y=" + randY;
var nID3 = "x=" + (randX + 2) + "&y=" + randY;
var nID4 = "x=" + (randX + 3) + "&y=" + randY;
if (($("#nID").hasClass("boat")) || ($("#nID2").hasClass("boat")) || ($("#nID3").hasClass("boat")) || ($("#nID4").hasClass("boat"))) {
generateBoats();
}
else {
$(document.getElementById(nID)).addClass("boat");
$(document.getElementById(nID2)).addClass("boat");
$(document.getElementById(nID3)).addClass("boat");
$(document.getElementById(nID4)).addClass("boat");
}
}
else {
generateBoats();
}
}
else if (rotation == 1) {
if (randY < 8) {
var nID = "x=" + randX + "&y=" + randY;
var nID2 = "x=" + randX + "&y=" + (randY + 1);
var nID3 = "x=" + randX + "&y=" + (randY + 2);
var nID4 = "x=" + randX + "&y=" + (randY + 3);
if (($("#nID").hasClass("boat")) || ($("#nID2").hasClass("boat")) || ($("#nID3").hasClass("boat")) || ($("#nID4").hasClass("boat"))) {
generateBoats();
}
else {
$(document.getElementById(nID)).addClass("boat");
$(document.getElementById(nID2)).addClass("boat");
$(document.getElementById(nID3)).addClass("boat");
$(document.getElementById(nID4)).addClass("boat");
}
}
else {
generateBoats();
}
}
}
</script>
</head>
<body onload="generateBoats()">
<table id="tabela"></table>
</body>
</html>

Add alt and title tags to images with the help of JavaScript

I have this script that uses the blogger feed to pull the content.
It pulls text and image from the article.
It would be perfect if the Alt and Title tags were added to the images, does anyone have any idea how to do this?
<div id="feed-list-container">
</div>
<div style="clear:both;">
</div>
<style>
div[data-tag=''] {float: left;
positon: relative;
width: 26%;
background-color: #9cb5c2;
}
</style>
<script type='text/javascript'>
var multiFeed = {
feedsUri: [
{
name: "Terror",
url: "https://elfenliedbrazil.blogspot.com/",
tag: "Terror"
},
],
numPost: 18,
showThumbnail: true,
showSummary: true,
summaryLength: 200,
titleLength:"auto",
thumbSize: 200,
containerId: "feed-list-container",
readMore: {
text: "",
endParam: "?max-results=20"
}
};
</script>
This is my code so far:
var mf_defaults = {
feedsUri: [{
name: "Posting JQuery",
url: " ",
tag: "JQuery"
}, {
name: "Posting CSS",
url: "",
tag: "CSS"
}, {
name: "Widget-Widget Blogger",
url: " ",
tag: "Widget"
}],
numPost: 4,
showThumbnail: true,
showSummary: true,
summaryLength: 80,
titleLength: "auto",
thumbSize: 200,
thumbWidth: 200, // new setting
thumbHeight: 90, // new setting
newTabLink: false,
containerId: "feed-list-container",
listClass: "list-entries",
readMore: {
text: "More",
endParam: "?max-results=20"
},
autoHeight: false,
current: 0,
onLoadFeed: function(a) {},
onLoadComplete: function() {},
loadFeed: function(c) {
var d = document.getElementsByTagName("head")[0],
a = document.getElementById(this.containerId),
b = document.createElement("script");
b.type = "text/javascript";
b.src = this.feedsUri[c].url + "/feeds/posts/summary" + (this.feedsUri[c].tag ? "/-/" + this.feedsUri[c].tag : "") + "?alt=json-in-script&max-results=" + this.numPost + "&callback=listEntries";
d.appendChild(b)
}
};
for(var i in mf_defaults) {
mf_defaults[i] = (typeof(multiFeed[i]) !== undefined && typeof(multiFeed[i]) !== "undefined") ? multiFeed[i] : mf_defaults[i]
}
function listEntries(q) {
var p = q.feed.entry,
c = mf_defaults,
h = document.getElementById(c.containerId),
a = document.createElement("div"),
d = "",
l = c.feedsUri.length,
n, k, m, g;
for(var f = 0; f < c.numPost; f++) {
if(f == p.length) {
break
}
n = (c.titleLength !== "auto") ? p[f].title.$t.substring(0, c.titleLength) + (c.titleLength < p[f].title.$t.length ? "…" : "") : p[f].title.$t;
m = ("summary" in p[f]) ? p[f].summary.$t.replace(/<br ?\/?>/g, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : "";
m = (c.summaryLength < m.length) ? m.substring(0, c.summaryLength) + "…" : m;
g = ("media$thumbnail" in p[f]) ? '<img src="' + p[f].media$thumbnail.url.replace(/\/s72(\-c)?\//, "/w" + c.thumbWidth + "-h" + c.thumbHeight + "-c/") + '" style="width:' + c.thumbWidth + "px;height:" + c.thumbHeight + 'px;">' : '';
for(var e = 0, b = p[f].link.length; e < b; e++) {
k = (p[f].link[e].rel == "alternate") ? p[f].link[e].href : "#"
}
d += '<div data-tag="'+c.feedsUri[c.current].tag+'" class="post hentry"' + (!c.autoHeight ? ' style="height' + c.thumbHeight + 'px;overflow:hidden; border-width:1px; border-style: solid; border-color: #000000; height: 200px"' : "") + ">";
d += '<div class="post-title-2" style=" height: 38px;"><h2 style=" font-size: 13px; ">" + n + "</h2></div>";
d += (c.showThumbnail) ? g : "";
d += '<div class="summary">';
d += "<span" + (!c.showSummary ? ' style="display:none;"' : "") + ">";
d += (c.showSummary) ? m : "";
d += "</span></div>";
d += '<span style="display:block;clear:both;"></span></div>'
}
d += "";
d += '<div class="more-link">" + c.readMore.text + "</div>";
a.className = c.listClass;
a.innerHTML = '<div data-tag=" margin-top: -33px;'+c.feedsUri[c.current].tag+'" +class="main-title"><h2>' + c.feedsUri[c.current].name + "</h2></div>" + d;
h.appendChild(a);
c.onLoadFeed(c.current);
if((c.current + 1) < l) {
c.loadFeed(c.current + 1)
}
if((c.current + 1) == l) {
c.onLoadComplete()
}
c.current++
}
mf_defaults.loadFeed(0);
I believe that the party that is responsible for pulling the image is img
This may be a stupid answer... but from what I understand of your question, have you tried this?
g = ("media$thumbnail" in p[f]) ? '<img src="' + p[f].media$thumbnail.url.replace(/\/s72(\-c)?\//, "/w" + c.thumbWidth + "-h" + c.thumbHeight + "-c/") + '" style="width:' + c.thumbWidth + "px;height:" + c.thumbHeight + 'px;" title="' + n + '" alt="' + n + '">' : '';

How to create a pop up when I click on any item of this tree

I want to show a div when I click on any item of the tree here
the tree is loaded in the index.html via this iframe
<IFRAME NAME="treeframe" ID="treeframe" SRC="tree.htm?150921" CLASS="fullsize" FRAMEBORDER="0" SCROLLING="no"></IFRAME>
the element ('.di')
is generated with js
var v = document.createElement("div");
v.className = "di";
var s = v.style;
s.width = sz.Tew + "px";
s.height = sh + "px";
s.left = (sx - (sz.Tew / 2)) + "px";
s.top = (sy - (sh / 2)) + "px";
if (wp) {
v.onmousedown = TCT;
v.id = i;
v.pid = e.p.i;
o.ps[i] = {
x: sx,
y: sy
};
}
var tn = e.p.hp ? (mn ? fn : (e.p.h + (sn ? (" " + sn) : ""))) : e.p.h;
v.innerHTML = "<TABLE WIDTH=\"100%\" HEIGHT=\"100%\" STYLE=\"table-layout:fixed;\">" + "<TR><TD CLASS=\"" + cc + "\" STYLE=\"font-size:" + (e.d ? sz.Tds : sz.Tfs) + "px;color:" + _4 + "\"" + " TITLE=\"" + (e.d ? "Duplicate: " : "") + EH(fn) + "\">" + (e.d ? "<I>Duplicate:</I><BR>" : "") + (e.m ? "<B>" : "") + EL(tn) + (e.m ? "</B>" : "") + "</TD></TR>" + rs + "</TABLE>";
o.appendChild(v);
I typed this code but it's not working:
jQuery(window).load( function(){
jQuery('.di').on( 'click', function ( _ev ) {
jQuery('.sidebar-wrapper').fadeIn(500);
});
jQuery('.sidebar-wrapper .sidebar-close').on( 'click', function ( _ev ) {
jQuery('.sidebar-wrapper').fadeOut(500);
});
});
jQuery(document).ready( function(){
jQuery('body').on( 'click','.dcelld', function ( _ev ) {
jQuery('.sidebar-wrapper').fadeIn(500);
});
jQuery('body').on( 'click','.sidebar-wrapper .sidebar-close', function ( _ev ) {
jQuery('.sidebar-wrapper').fadeOut(500);
});
});

Subfunction Not Working

My function formatMoney works when called from recalculateReservationFee() but my javascript console gives me the error "undefined function" when I try to call formatMoney from a sub function named recalculateGrandTotal() that's inside of recalculateReservationFee(). I don't understand why this is happening, how can I rescope the methods to access formatMoney from recalculateGrandTotal()?
Here's my code:
//money formatter from... http://stackoverflow.com/questions/9318674/javascript-number-currency-formatting
Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
var n = this,
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
decSeparator = decSeparator == undefined ? "." : decSeparator,
thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
sign = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};
function recalculateReservationFee() {
var vacationRentalPrice = parseFloat( <? php echo $vacationRentalPrice; ?> );
var TaxRate = parseFloat(document.getElementById("priceDisplayTaxRate").textContent);
var CleaningFee = parseFloat(document.getElementById("priceDisplayCleaningFee").textContent);
var PoolHeating = parseFloat(document.getElementById("priceDisplayPoolHeating").textContent);
var PetFee = parseFloat(document.getElementById("priceDisplayPetFee").textContent);
var PropertyDamageProtection = parseFloat(document.getElementById("priceDisplayPropertyDamageProtection").textContent);
var reservationFeeTarget = vacationRentalPrice + TaxRate + CleaningFee + PoolHeating + PetFee + PropertyDamageProtection;
var theNewReservationFee = parseFloat(( <? php echo $theReservationFeePercentage; ?> * reservationFeeTarget) / 100);
var formattedNewReservationFee = theNewReservationFee.formatMoney(2, ',', '.'); // example "$3,543.76"
document.getElementById("priceDisplayReservationFee").innerHTML = formattedNewReservationFee;
//document.write('<br/>The Vars: <br/>' + vacationRentalPrice + '<br/>' + CleaningFee + '<br/>' + TaxRate + '<br/>' + PoolHeating + '<br/>' + PetFee + '<br/>' + PropertyDamageProtection + '<br/>--<br/>' + reservationFeeTarget + '<br/>' + formattedNewReservationFee);
function recalculateGrandTotal() {
var theGrandTotal = vacationRentalPrice + <? php echo $theRefundableDamageDepositRounded; ?> +TaxRate + CleaningFee + PoolHeating + PetFee + PropertyDamageProtection + formattedNewReservationFee;
var formattedGrandTotal = theGrandTotal.formatMoney(2, ',', '.'); // example "$3,543.76"
document.getElementById("priceDisplayVacationPackageTotal").innerHTML = formattedGrandTotal;
document.getElementById("priceDisplayVacationPackageGrandTotal").innerHTML = formattedGrandTotal;
}
recalculateGrandTotal();
}
function clearFee(theNamedFee, theNamedClass) {
document.getElementById(theNamedFee).innerHTML = '0.00';
var elems = document.getElementsByClassName(theNamedClass);
for (var i = 0; i < elems.length; i++) {
elems[i].disabled = true;
}
recalculateReservationFee();
}
function showFee(theNamedFee, someFee, theNamedClass) {
document.getElementById(theNamedFee).innerHTML = someFee;
var elems = document.getElementsByClassName(theNamedClass);
for (var i = 0; i < elems.length; i++) {
elems[i].disabled = false;
}
recalculateReservationFee();
}
The line
var theGrandTotal = vacationRentalPrice + .... + formattedNewReservationFee;
^^^^^^^^^^^^^^^^^^^^^^^^^^
formattedNewReservationFee sounds like it is a string. number + "string" = "numberstring".

Change countdown when refresh the page?

I have my own webshop and on the home page i have a lot of products with countdown.
So whats the problem?
The problem is, when i have many javascripts on home page then the broser will freezing, getting slow.
How i know this is an javascript problem ? I tried to disable javascript on the browser and my website works normal.
/*!
*
* Brian2000: BK_Countdown v1.1
* AKA: Brian's jQuery Robust Date/Time Countdown
* http://brian2000.com
*
* Copyright 2012-2013, Brian Kennedy
* Licensed under the GPL Version 3 license
* http://www.gnu.org/licenses/gpl-3.0.en.html
*
* Date: Wed Jan 9 2013 2:54PM EST
*
* You can't remove this part, and if you make changes or improve things, please keep me informed.
* Thank you, enjoy, and support Open Source!
*/
/*
This portion explains how to use the counter, I recomend not deleting it either ;-)
VARS [required]
------------------------------------------------
container: ID of Element for counter
targetDate: MM/DD/YYYY
targetTime: HH:MM:SS (0-23 Hour) [seconds are optional]
OPTIONS:
------------------------------------------------
order: format/output order
order: 1 = Label + Spacer + Value
order: 2 = Value + Spacer + Label (reverse from order 1)
spacer: text/string seperator between label and value
element: html element for label and value containers (default is span)
end: Message to display when date has passed
dayOf: Message to display on day of counter expiration
*/
function BK_CountDown(container, targetDate, targetTime, opts) {
/////////////////////////////////////////////////////
//vars
this.opts = opts;
this.complete = false; //for exiting interval
this.container = container; //target
DArray = targetDate.split('/');
this.targetDate = DArray[0] + '/' + DArray[1] + '/' + DArray[2];
TArray = targetTime.split(':');
this.targetHour = TArray[0]; //hr
this.targetMin = TArray[1]; //min
if (typeof TArray[2] == 'undefined') { //sec
this.targetSec = 0;
}else{
this.targetSec = TArray[2];
}
/////////////////////////////////////////////////////
// options
var defaults = {
'order' : "1",
'spacer' : ':',
'element' : 'span',
'end' : "Deal is ended!",
'dayOf' : "Deal is ended!"
}
if(typeof this.opts != "undefined") { //if options were assigned...
for(var i in defaults) { //assign defaults for unchanged opts
if(typeof this.opts[i] == "undefined") {
this.opts[i] = defaults[i];
}
}
}else{ //no options were assigned
this.opts = defaults;
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// assembly
/////////////////////////////////////////////////////
s = this.opts['spacer'];
this.c = container.substring(1);
e = this.opts['element'];
if(this.opts['order'] == 2){
//reverse assembly
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">' + s + ' Days</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">' + s + ' :</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">' + s + ' :</' + e + '>');
}
else{
//default assembly
$(container).append('<' + e + ' id="' + this.c + '_txt_days" class="txt_days">Days ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_days" class="count_days"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_hours" class="txt_hours">Hours ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_hours" class="count_hours"></' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_txt_min" class="txt_min">Minutes ' + s + '</' + e + '>');
$(container).append('<' + e + ' id="' + this.c + '_count_min" class="count_min"></' + e + '>');
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//////// Count Update function
this.count_update = function count_update(){
date = new Date(); //NOW
targetDate = new Date(this.targetDate);
targetDate.setHours(this.targetHour);
targetDate.setMinutes(this.targetMin);
targetDate.setSeconds(this.targetSec);
var UDate = Math.round(date.getTime()/1000);
var UTargetDate = Math.round(targetDate.getTime()/1000);
differance = UTargetDate - UDate;
days=Math.floor(differance/(60*60*24)*1);
hours=Math.floor((differance%(60*60*24))/(60*60)*1);
minutes=Math.floor(((differance%(60*60*24))%(60*60))/(60)*1);
seconds=Math.floor((((differance%(60*60*24))%(60*60))%(60))*1);
//if range is 0 don't display range
//days
if(days <= 0){$(this.container + '_count_days').remove();$(this.container + '_txt_days').remove();}
else{$(this.container + '_count_days').text(days);}
//hours
if(days <= 0 && hours <= 0){$(this.container + '_count_hours').remove();$(this.container + '_txt_hours').remove();}
else{$(this.container + '_count_hours').text(hours);}
//min
if(days <= 0 && hours <= 0 && minutes <= 0){$(this.container + '_count_min').remove();$(this.container + '_txt_min').remove();}
else{$(this.container + '_count_min').text(+minutes);}
//seconds
$(this.container + '_count_sec').text(seconds);
//Singular text for 'reverse' assembly
if(this.opts['order'] == 2){
if(days <= 1){$(this.container + '_txt_days').text(this.opts['spacer'] + ' dag en ');}
else{$(this.container + '_txt_days').text(this.opts['spacer'] + ' dagen en ')}
if(hours == 1){$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
else{$(this.container + '_txt_hours').text(this.opts['spacer'] + ' uur en ');}
if(minutes == 1){$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
else{$(this.container + '_txt_min').text(this.opts['spacer'] + ' min');}
if(seconds == 1){$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
else{$(this.container + '_txt_sec').text(this.opts['spacer'] + '');}
}
//end of countdown
if(days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0){
//timer is over, final output
//if date is today!
if(new Date().toDateString() == targetDate.toDateString()){
$(this.container).addClass('count_now');
$(this.container).text(this.opts['dayOf']);
}else{//if date is after today
$(this.container).addClass('count_end');
$(this.container).text(this.opts['end']);
}
this.complete = true;
}
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//run immediately
this.count_update();
//now loop this every second
var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
}
HTML:
$(document).ready(function() {
var aanbiedingcountdown = new BK_CountDown('#deal1', '05/25/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal2', '05/26/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal3', '05/28/2014', '23:57', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal4', '05/28/2014', '15:10', {order: 2, spacer: ''});
var aanbiedingcountdown = new BK_CountDown('#deal5', '05/26/2014', '23:57', {order: 2, spacer: ''});
});
You see, for every countdown that i want i need to create an ID.
But what i want is that when the page load, the countdown dont need to run, it makes my website slower. So, only when the someone refresh the page then he get the right date & time.
Example: Time is now 16:00u, the countdown are set at 17h, so, when someone is still on my website (10min) without refreshing the page then the countdown is still 16h only if he refresh the page then countdown is 16:10h...
I've seen this on other websites and they have more than 100 products with countdowns on the same page and still works perfect because timer is not running only if people refresh the page the the timer will set to right date & time.
Demo: http://jsfiddle.net/uJk73/ (i removed seconds, i though site will go faster without this, but no succes)
Hope someone can help my with this.
Updated jsfiddle
So let's say you had 9 deals
<div id="countdowntimer">
<div id="deal1"></div>
<div id="deal2"></div>
<div id="deal3"></div>
<div id="deal4"></div>
<div id="deal5"></div>
<div id="deal6"></div>
<div id="deal7"></div>
<div id="deal8"></div>
<div id="deal9"></div>
</div>
Get rid of this loop in BK_CountDown()
//now loop this every second
/*var selfobject = this; //scope gets lost within setInterval (see: http://www.vonloesch.de/node/32)
var theCounter = setInterval(function(){
selfobject.count_update();
if(selfobject.complete == true){
clearInterval(theCounter);}
}, 1000);
*/
Then
$(document).ready(function() {
var deals = []; // create an array
deals.push( new BK_CountDown('#deal1', '05/24/2014', '23:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal2', '05/24/2014', '22:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal3', '05/24/2014', '12:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal4', '05/24/2014', '13:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal5', '05/24/2014', '14:49', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal6', '05/24/2014', '15:57', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal7', '05/24/2014', '15:58', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal8', '05/24/2014', '15:59', {order: 2, spacer: ''}) );
deals.push( new BK_CountDown('#deal9', '05/24/2014', '16:00', {order: 2, spacer: ''}) );
var dealcounter = setInterval(function(){ // create one setTimeout
if (deals.length){
for (i in deals){
var selfobject = deals[i];
selfobject.count_update();
if(selfobject.complete == true) delete deals[i]; // remove from array
}
}else{
clearTimeout(dealcounter); // no more to count down, stop this loop
}
}, 5000); // 5 seconds
});

Categories