I have rendered fullcalendar event months week and day view. but I want some events only into month view and some other events only into week view and rest for day view. Is there any way to fulfill this. Hope you understand.
function BookingCalendar() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#bookingCalendar').fullCalendar({
theme: false,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
slotEventOverlap: false,
events: {
url: 'Booking',
type: 'POST',
data: {
//companyId: $('#CompanyID').val(),
companyId: 0,
}
},
eventRender: function(event, element) {
var toolTipContent = '';
var count = 0;
if (event.itemcode != '') {
var strItemCode = event.itemcode.split(";");
for (var i = 0; i < strItemCode.length; i++) {
count++;
toolTipContent = toolTipContent + strItemCode[i] + '<br />';
if (count > 3) {
toolTipContent = toolTipContent + '...' + '<br />';
break;
}
}
}
else
{
if (event.id != '') {
toolTipContent = toolTipContent + event.id + '<br/>';
}
if (event.CustomerName != '') {
toolTipContent = toolTipContent + event.CustomerName + '<br/>';
}
if (event.ShipAddress != '') {
toolTipContent = toolTipContent + event.ShipAddress + '<br/>';
}
if (event.ShipCity != '') {
toolTipContent = toolTipContent + event.ShipCity + ',';
}
if (event.ShipState != '') {
toolTipContent = toolTipContent + event.ShipState + ' - ';
}
if (event.ShipPostalCode != '') {
toolTipContent = toolTipContent + event.ShipPostalCode + '<br/>';
}
if (event.Country != '') {
toolTipContent = toolTipContent + event.Country + '<br/>';
}
if (event.Email != '') {
toolTipContent = toolTipContent + 'E: ' + event.Email + '<br/>';
}
if (event.Phone != '') {
toolTipContent = toolTipContent + 'P: ' + event.Phone;
}
if (event.Phone != '') {
toolTipContent = toolTipContent + 'P: ' + event.Phone;
}
}
element.qtip({
content: toolTipContent,
position: { corner: { tooltip: 'bottomLeft', target: 'topRight' } },
style: {
border: {
width: 1,
radius: 3,
color: '#2779AA'
},
padding: 10,
textAlign: 'left',
tip: true, // Give it a speech bubble tip with automatic corner detection
name: 'cream' // Style it according to the preset 'cream' style
}
});
}
});
}
Sure this is possible!
You can achieve this in the eventRender callback.
eventRender: function(event, element, view) {
var toolTipContent = 'This item is viewable in '+view.type;
var count = 0;
console.log(view.type);
console.log(event.viewableIn);
console.log(element);
if( $.inArray( view.type,event.viewableIn ) == -1 ){
element.length = 0; // This is the trick to "remove" the element.
}
console.log(element); // To check the element again...
console.log(); // Just an empty line in console.log().
}
This compares the view.type with the array values of the event's "non-standards field" I added.
viewableIn: ["month","agendaWeek","agendaDay"]
Look at my Fiddle and closely check each views (check day: 2016-07-20).
I'm working on a timeline display and I have data that I want to show on the tooltip. currently it only shows the value at each time. and I cannot find a way to change it. the example below shows how to change the value's format but not what values are displayed
var chart = c3.generate({
data: {
columns: [
['data1', 30000, 20000, 10000, 40000, 15000, 250000],
['data2', 100, 200, 100, 40, 150, 250]
],
axes: {
data2: 'y2'
}
},
axis : {
y : {
tick: {
format: d3.format("s")
}
},
y2: {
show: true,
tick: {
format: d3.format("$")
}
}
},
tooltip: {
format: {
title: function (d) { return 'Data ' + d; },
value: function (value, ratio, id) {
var format = id === 'data1' ? d3.format(',') : d3.format('$');
return format(value);
}
//value: d3.format(',') // apply this format to both y and y2
}
}
});
it's taken from http://c3js.org/samples/tooltip_format.html
they do admit that there isn't an example for content editing but I couldn't find anything in the reference or forums, but a suggestion to change the code (it's here: https://github.com/masayuki0812/c3/blob/master/c3.js in line 300) and below:
__tooltip_contents = getConfig(['tooltip', 'contents'], function (d, defaultTitleFormat, defaultValueFormat, color) {
var titleFormat = __tooltip_format_title ? __tooltip_format_title : defaultTitleFormat,
nameFormat = __tooltip_format_name ? __tooltip_format_name : function (name) { return name; },
valueFormat = __tooltip_format_value ? __tooltip_format_value : defaultValueFormat,
text, i, title, value, name, bgcolor;
for (i = 0; i < d.length; i++) {
if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
if (! text) {
title = titleFormat ? titleFormat(d[i].x) : d[i].x;
text = "<table class='" + CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
name = nameFormat(d[i].name);
value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
bgcolor = levelColor ? levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
return text + "</table>";
})
did anyone attempted to do so? developed some function to facilitate the process? have any tips on how to do so correctly? I do not know how to change their code in a way I could use more data or data different than the d value the function gets.
If you use the function getTooltipContent from https://github.com/masayuki0812/c3/blob/master/src/tooltip.js#L27 and add it in the chart declaration, in tooltip.contents, you'll have the same tooltip content that the default one.
You can make changes on this code and customize it as you like. One detail, as CLASS is not defined in the current scope, but it's part chart object, I substituted CLASS for $$.CLASS, maybe you don't even need this Object in your code.
var chart = c3.generate({
/*...*/
tooltip: {
format: {
/*...*/
},
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor;
for (i = 0; i < d.length; i++) {
if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
if (! text) {
title = titleFormat ? titleFormat(d[i].x) : d[i].x;
text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
name = nameFormat(d[i].name);
value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + $$.CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
return text + "</table>";
}
}
});
If you want to control tooltip render and use default rendering depending on data value you can use something like this:
tooltip: {
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
if (d[1].value > 0) {
// Use default rendering
return this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color);
} else {
return '<div>Show what you want</div>';
}
},
format: {
/**/
}
}
In my case i had to add the day for the date value(x axis) in tool tip. Finally i came came up with the below solution
References for js and css
https://code.jquery.com/jquery-3.2.1.js
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js
https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js
https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css
function toDate(dateStr)
{
var numbers = dateStr.match(/\d+/g);
return new Date(numbers[0], numbers[1]-1, numbers[2]);
}
function GetMonthFromString(month)
{
var months = {'Jan' : '01','Feb' : '02','Mar':'03','Apr':'04',
'May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09',
'Oct':'10','Nov':'11','Dec':'12'};
return months[month];
}
function GetFullDayName(formatteddate)
{
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var dayofdate = weekday[formatteddate.getDay()];
return dayofdate;
}
//Chart Data for x-axis, OnHours and AvgHours
function CollectChartData()
{
var xData = new Array();
var onHoursData = new Array();
var averageHoursData = new Array();
var instanceOccuringDatesArray = ["2017-04-20","2017-04-21","2017-04-22","2017-04-23","2017-04-24","2017-04-25","2017-04-26","2017-04-27","2017-04-28","2017-04-29","2017-04-30","2017-05-01","2017-05-02","2017-05-03","2017-05-04","2017-05-05","2017-05-06","2017-05-07","2017-05-08","2017-05-09","2017-05-10","2017-05-11","2017-05-12","2017-05-13","2017-05-14","2017-05-15","2017-05-16","2017-05-17","2017-05-18","2017-05-19","2017-05-20"];
var engineOnHoursArray = ["4.01","14.38","0.10","0.12","0.01","0.24","0.03","6.56","0.15","0.00","1.15","0.00","1.21","2.06","8.55","1.41","0.03","1.42","0.00","3.35","0.02","3.44","0.05","5.41","4.06","0.02","0.04","7.26","1.02","5.09","0.00"];
var avgUtilizationArray = ["2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29","2.29"];
xData.push('x');
onHoursData.push('OnHours');
averageHoursData.push('Project Average');
for(var index=0;index<instanceOccuringDatesArray.length;index++)
{
xData.push(instanceOccuringDatesArray[index]);
}
for(var index=0;index<engineOnHoursArray.length;index++)
{
onHoursData.push(engineOnHoursArray[index]);
}
for(var index=0;index<avgUtilizationArray.length;index++)
{
averageHoursData.push(avgUtilizationArray[index]);
}
var Data = [xData, onHoursData, averageHoursData];
return Data;
}
function tooltip_contents(d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config, CLASS = $$.CLASS,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor;
// You can access all of data like this:
//$$.data.targets;
for (i = 0; i < d.length; i++) {
if (! text) {
title = titleFormat ? titleFormat(d[i].x) : d[i].x;
var arr = title.split(" ");
var datestr = new Date().getFullYear().toString() + "-"+ GetMonthFromString(arr[1]) + "-"+ arr[0];
var formatteddate = toDate(datestr);
var dayname = GetFullDayName(formatteddate);
title = title + " (" + dayname + ")";
text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
name = nameFormat(d[i].name);
var initialvalue = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
if (initialvalue.toString().indexOf('.') > -1)
{
var arrval = initialvalue.toString().split(".");
value = arrval[0] + "h " + arrval[1] + "m";
}
else
{
value = initialvalue + "h " + "00m";
}
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
return text + "</table>";
}
$(document).ready(function () {
var Data = CollectChartData();
var chart = c3.generate({
data: {
x: 'x',
columns: Data
},
axis: {
x: {
type: 'timeseries',
tick: {
rotate: 75,
//format: '%d-%m-%Y'
format: '%d %b'
}
},
y : {
tick : {
format: function (y) {
if (y < 0) {
}
return y;
}
},
min : 0,
padding : {
bottom : 0
}
}
},
tooltip: {
contents: tooltip_contents
}
});
});
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />
<div id="chart"></div>
When we have a stacked bar chart and we would like to show "Total" in the tooltip (but not in the chart as a bar/stack) this can come handy.
C3 charts use a array to store the data for tooltips and before the tooltips are displayed we are adding totals (or anyother data as per our requirement). By doing this though the totals is not available as a stack it is shown in the tooltip.
function key_for_sum(arr) {
return arr.value; //value is the key
};
function sum(prev, next) {
return prev + next;
}
var totals_object = {};
totals_object.x = d[0]['x'];
totals_object.value = d.map(key_for_sum).reduce(sum);
totals_object.name = 'total';
totals_object.index = d[0]['index'];
totals_object.id = 'total';
d.push(totals_object);
Above code has been added to ensure that total is available in
C3.js Stacked Bar chart's tooltip
var chart = c3.generate({
/*...*/
tooltip: {
format: {
/*...*/
},
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
function key_for_sum(arr) {
return arr.value; //value is the key
}
function sum(prev, next) {
return prev + next;
}
var totals_object = {};
totals_object.x = d[0]['x'];
totals_object.value = d.map(key_for_sum).reduce(sum);// sum func
totals_object.name = 'total';//total will be shown in tooltip
totals_object.index = d[0]['index'];
totals_object.id = 'total';//c3 will use this
d.push(totals_object);
var $$ = this,
config = $$.config,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) {
return name;
},
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor;
for (i = 0; i < d.length; i++) {
if (!(d[i] && (d[i].value || d[i].value === 0))) {
continue;
}
if (!text) {
title = titleFormat ? titleFormat(d[i].x) : d[i].x;
text = "<table class='" + $$.CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
name = nameFormat(d[i].name);
value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + $$.CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
return text + "</table>";
}
}
Adding additional content or non-numerical data into the chart tooltips can be done.
This builds on #supita's excellent answer http://stackoverflow.com/a/25750639/1003746.
Its possible to insert additional metadata about each line into the classes parameter when generating/updating the chart. These can then be added as rows to the tooltip.
This doesn't seem to affect the chart - unless you are using the data.classes feature.
data: {
classes: {
data1: [{prop1: 10, prop2: 20}, {prop1: 30, prop2: 40}],
data2: [{prop1: 50, prop2: 60}'{prop1: 70, prop2: 80}]
}
}
To pick up the metadata in the config.
tooltip: {
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
const $$ = this;
const config = $$.config;
const meta = config.data_classes;
...
for (i = 0; i < d.length; i++) {
if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
if (! text) {
...
}
const line = d[0].id;
const properties = meta.classes[line];
const property = properties? properties[i] : null;
Then add the following rows to the table to show the new properties.
if (property ) {
text += "<tr class='" + $$.CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>PROP1</td>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + property.prop1 + "</td>";
text += "</tr>";
text += "<tr class='" + $$.CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>PROP2</td>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" +
property.prop2+ " cm/s</td>";
If anybody cares, here is a ClojureScript version of the above algorithm (e.g. supita's answer), slightly simplified (without support for config). (This is probably nothing the OP asked for, but as of now there are so few resources on the net on this topic that most people might wind up here.)
:tooltip {
:contents
(fn [d default-title-format default-value-format color]
(this-as this
(let [this-CLASS (js->clj (.-CLASS this) :keywordize-keys true)
tooltip-name-class (:tooltipName this-CLASS)
rows (js->clj d :keywordize-keys true)
title-row (->> (first rows) (#(str "<table class='" (:tooltip this-CLASS)
"'><tr><th colspan='2'>"
(default-title-format (:x %)) "</th></tr>")))
data-rows (->> rows
(map #(str "<tr class='" tooltip-name-class "--" (:id %) "'>"
"<td class='name'><span style='background-color:"
(color (:id %)) "'></span>" (:name %) "</td>"
"<td class='value'>" (default-value-format (:value %)) "</td>"
"</tr>")))]
(str title-row (string/join data-rows) "</table>"))))}
Your question is about changing the content of the tooltip in c3js.
The tooltip has 3 variables
+----------------+
| title |
+----------------+
| name | value |
+----------------+
Plus, you want to add 'name' from an additional variable, other than those used in 'column'.
tooltip: {
format: {
title(x, index) { return ''; },
name(name, ratio, id, index) { return lst[index + 1]; },
value(value, ratio, id, index) { return value; }
}
},
this worked for me, feel free to play around with the arguments, to get what you need.
I faced a problem which is related tooltip position and style for c3 before. in order to arrange tooltip in c3 freely, my suggestion is manipulating tooltip with d3.
// internal = chart.internal()
const mousePos = d3.mouse(internal.svg.node()); // find mouse position
const clientX = mousePos[0]; //for x
const clientY = mousePos[1]; //for y
const tooltip = d3.select("#tooltip"); //select tooltip div (apply your style)
tooltip.style("display", "initial"); //show tooltip
tooltip.style("left", clientX - mouseOffSet.X + "px"); // set position
tooltip.style("top", clientY - mouseOffSet.Y + "px"); // set position
tooltip.html("<span>" + content + "</span>");
// you can arrange all content and style whatever you want
<div
id="tooltip"
className="your-style"
style={{ display: "none", position: "absolute" }}
/>
Good luck!!
This is a really great slider but it has just one annoying fault. If I have different widths of images, the ones that are too small for the default width, are left justified. I've tried every which way to do it with the html/css but it's somewhere in the js I think. I even loaded the js after the images load and it still put it left justified even though they were centered for that split second before the js loaded. What seems to happen is, the js takes the smaller width image and makes it the full default width and adds whitespace to the right of it, essentially making it a full width image. I am just curious if this is customizable so that the photo is centered and whitespace is added on either side.
Any thoughts are appreciated, thanks for taking a look.
(function ($) {
var params = new Array;
var order = new Array;
var images = new Array;
var links = new Array;
var linksTarget = new Array;
var titles = new Array;
var interval = new Array;
var imagePos = new Array;
var appInterval = new Array;
var squarePos = new Array;
var reverse = new Array;
$.fn.coinslider = $.fn.CoinSlider = function (options) {
init = function (el) {
order[el.id] = new Array();
images[el.id] = new Array();
links[el.id] = new Array();
linksTarget[el.id] = new Array();
titles[el.id] = new Array();
imagePos[el.id] = 0;
squarePos[el.id] = 0;
reverse[el.id] = 1;
params[el.id] = $.extend({}, $.fn.coinslider.defaults, options);
$.each($('#' + el.id + ' img'), function (i, item) {
images[el.id][i] = $(item).attr('src');
links[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('href') : '';
linksTarget[el.id][i] = $(item).parent().is('a') ? $(item).parent().attr('target') : '';
titles[el.id][i] = $(item).next().is('span') ? $(item).next().html() : '';
$(item).hide();
$(item).next().hide();
});
$(el).css({
'background-image': 'url(' + images[el.id][0] + ')',
'width': params[el.id].width,
'height': params[el.id].height,
'position': 'relative',
'background-position': 'top left'
}).wrap("<div class='coin-slider' id='coin-slider-" + el.id + "' />");
$('#' + el.id).append("<div class='cs-title' id='cs-title-" + el.id + "' style='position: absolute; bottom:0; left: 0; z-index: 1000;'></div>");
$.setFields(el);
if (params[el.id].navigation) $.setNavigation(el);
$.transition(el, 0);
$.transitionCall(el);
}
$.setFields = function (el) {
tWidth = sWidth = parseInt(params[el.id].width / params[el.id].spw);
tHeight = sHeight = parseInt(params[el.id].height / params[el.id].sph);
counter = sLeft = sTop = 0;
tgapx = gapx = params[el.id].width - params[el.id].spw * sWidth;
tgapy = gapy = params[el.id].height - params[el.id].sph * sHeight;
for (i = 1; i <= params[el.id].sph; i++) {
gapx = tgapx;
if (gapy > 0) {
gapy--;
sHeight = tHeight + 1;
} else {
sHeight = tHeight;
}
for (j = 1; j <= params[el.id].spw; j++) {
if (gapx > 0) {
gapx--;
sWidth = tWidth + 1;
} else {
sWidth = tWidth;
}
order[el.id][counter] = i + '' + j;
counter++;
if (params[el.id].links) $('#' + el.id).append("<a href='" + links[el.id][0] + "' class='cs-" + el.id + "' id='cs-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></a>");
else $('#' + el.id).append("<div class='cs-" + el.id + "' id='cs-" + el.id + i + j + "' style='width:" + sWidth + "px; height:" + sHeight + "px; float: left; position: absolute;'></div>");
$("#cs-" + el.id + i + j).css({
'background-position': -sLeft + 'px ' + (-sTop + 'px'),
'left': sLeft,
'top': sTop
});
sLeft += sWidth;
}
sTop += sHeight;
sLeft = 0;
}
$('.cs-' + el.id).mouseover(function () {
$('#cs-navigation-' + el.id).show();
});
$('.cs-' + el.id).mouseout(function () {
$('#cs-navigation-' + el.id).hide();
});
$('#cs-title-' + el.id).mouseover(function () {
$('#cs-navigation-' + el.id).show();
});
$('#cs-title-' + el.id).mouseout(function () {
$('#cs-navigation-' + el.id).hide();
});
if (params[el.id].hoverPause) {
$('.cs-' + el.id).mouseover(function () {
params[el.id].pause = true;
});
$('.cs-' + el.id).mouseout(function () {
params[el.id].pause = false;
});
$('#cs-title-' + el.id).mouseover(function () {
params[el.id].pause = true;
});
$('#cs-title-' + el.id).mouseout(function () {
params[el.id].pause = false;
});
}
};
$.transitionCall = function (el) {
clearInterval(interval[el.id]);
delay = params[el.id].delay + params[el.id].spw * params[el.id].sph * params[el.id].sDelay;
interval[el.id] = setInterval(function () {
$.transition(el)
}, delay);
}
$.transition = function (el, direction) {
if (params[el.id].pause == true) return;
$.effect(el);
squarePos[el.id] = 0;
appInterval[el.id] = setInterval(function () {
$.appereance(el, order[el.id][squarePos[el.id]])
}, params[el.id].sDelay);
$(el).css({
'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')'
});
if (typeof (direction) == "undefined") imagePos[el.id]++;
else if (direction == 'prev') imagePos[el.id]--;
else imagePos[el.id] = direction;
if (imagePos[el.id] == images[el.id].length) {
imagePos[el.id] = 0;
}
if (imagePos[el.id] == -1) {
imagePos[el.id] = images[el.id].length - 1;
}
$('.cs-button-' + el.id).removeClass('cs-active');
$('#cs-button-' + el.id + "-" + (imagePos[el.id] + 1)).addClass('cs-active');
if (titles[el.id][imagePos[el.id]]) {
$('#cs-title-' + el.id).css({
'opacity': 0
}).animate({
'opacity': params[el.id].opacity
}, params[el.id].titleSpeed);
$('#cs-title-' + el.id).html(titles[el.id][imagePos[el.id]]);
} else {
$('#cs-title-' + el.id).css('opacity', 0);
}
};
$.appereance = function (el, sid) {
$('.cs-' + el.id).attr('href', links[el.id][imagePos[el.id]]).attr('target', linksTarget[el.id][imagePos[el.id]]);
if (squarePos[el.id] == params[el.id].spw * params[el.id].sph) {
clearInterval(appInterval[el.id]);
return;
}
$('#cs-' + el.id + sid).css({
opacity: 0,
'background-image': 'url(' + images[el.id][imagePos[el.id]] + ')',
'background-repeat': 'no-repeat',
'background-color': '#fff',
});
$('#cs-' + el.id + sid).animate({
opacity: 1
}, 300);
squarePos[el.id]++;
};
$.setNavigation = function (el) {
$(el).append("<div id='cs-navigation-" + el.id + "'></div>");
$('#cs-navigation-' + el.id).hide();
$('#cs-navigation-' + el.id).append("<a href='#' id='cs-prev-" + el.id + "' class='cs-prev'></a>");
$('#cs-navigation-' + el.id).append("<a href='#' id='cs-next-" + el.id + "' class='cs-next'></a>");
$('#cs-prev-' + el.id).css({
'position': 'absolute',
'top': 0,
'left': 0,
'z-index': 1001,
'line-height': '30px',
'opacity': params[el.id].opacity
}).click(function (e) {
e.preventDefault();
$.transition(el, 'prev');
$.transitionCall(el);
}).mouseover(function () {
$('#cs-navigation-' + el.id).show()
});
$('#cs-next-' + el.id).css({
'position': 'absolute',
'top': 0,
'right': 0,
'z-index': 1001,
'line-height': '30px',
'opacity': params[el.id].opacity
}).click(function (e) {
e.preventDefault();
$.transition(el);
$.transitionCall(el);
}).mouseover(function () {
$('#cs-navigation-' + el.id).show()
});
$("<div id='cs-buttons-" + el.id + "' class='cs-buttons'></div>").appendTo($('#coin-slider-' + el.id));
for (k = 1; k < images[el.id].length + 1; k++) {
$('#cs-buttons-' + el.id).append("<a href='#' class='cs-button-" + el.id + "' id='cs-button-" + el.id + "-" + k + "'>" + k + "</a>");
}
$.each($('.cs-button-' + el.id), function (i, item) {
$(item).click(function (e) {
$('.cs-button-' + el.id).removeClass('cs-active');
$(this).addClass('cs-active');
e.preventDefault();
$.transition(el, i);
$.transitionCall(el);
})
});
$('#cs-navigation-' + el.id + ' a').mouseout(function () {
$('#cs-navigation-' + el.id).hide();
params[el.id].pause = false;
});
$("#cs-buttons-" + el.id) /*.css({'right':'50%','margin-left':-images[el.id].length*15/2-5,'position':'relative'})*/
;
}
$.effect = function (el) {
effA = ['random', 'swirl', 'rain', 'straight'];
if (params[el.id].effect == '') eff = effA[Math.floor(Math.random() * (effA.length))];
else eff = params[el.id].effect;
order[el.id] = new Array();
if (eff == 'random') {
counter = 0;
for (i = 1; i <= params[el.id].sph; i++) {
for (j = 1; j <= params[el.id].spw; j++) {
order[el.id][counter] = i + '' + j;
counter++;
}
}
$.random(order[el.id]);
}
if (eff == 'rain') {
$.rain(el);
}
if (eff == 'swirl') $.swirl(el);
if (eff == 'straight') $.straight(el);
reverse[el.id] *= -1;
if (reverse[el.id] > 0) {
order[el.id].reverse();
}
}
$.random = function (arr) {
var i = arr.length;
if (i == 0) return false;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var tempi = arr[i];
var tempj = arr[j];
arr[i] = tempj;
arr[j] = tempi;
}
}
$.swirl = function (el) {
var n = params[el.id].sph;
var m = params[el.id].spw;
var x = 1;
var y = 1;
var going = 0;
var num = 0;
var c = 0;
var dowhile = true;
while (dowhile) {
num = (going == 0 || going == 2) ? m : n;
for (i = 1; i <= num; i++) {
order[el.id][c] = x + '' + y;
c++;
if (i != num) {
switch (going) {
case 0:
y++;
break;
case 1:
x++;
break;
case 2:
y--;
break;
case 3:
x--;
break;
}
}
}
going = (going + 1) % 4;
switch (going) {
case 0:
m--;
y++;
break;
case 1:
n--;
x++;
break;
case 2:
m--;
y--;
break;
case 3:
n--;
x--;
break;
}
check = $.max(n, m) - $.min(n, m);
if (m <= check && n <= check) dowhile = false;
}
}
$.rain = function (el) {
var n = params[el.id].sph;
var m = params[el.id].spw;
var c = 0;
var to = to2 = from = 1;
var dowhile = true;
while (dowhile) {
for (i = from; i <= to; i++) {
order[el.id][c] = i + '' + parseInt(to2 - i + 1);
c++;
}
to2++;
if (to < n && to2 < m && n < m) {
to++;
}
if (to < n && n >= m) {
to++;
}
if (to2 > m) {
from++;
}
if (from > to) dowhile = false;
}
}
$.straight = function (el) {
counter = 0;
for (i = 1; i <= params[el.id].sph; i++) {
for (j = 1; j <= params[el.id].spw; j++) {
order[el.id][counter] = i + '' + j;
counter++;
}
}
}
$.min = function (n, m) {
if (n > m) return m;
else return n;
}
$.max = function (n, m) {
if (n < m) return m;
else return n;
}
this.each(function () {
init(this);
});
};
$.fn.coinslider.defaults = {
width: 828,
height: 200,
spw: 1,
sph: 1,
delay: 4000,
sDelay: 30,
opacity: 0.7,
titleSpeed: 500,
effect: '',
navigation: true,
links: false,
hoverPause: true
};
})(jQuery);
It seems to be taking the image source url and putting it into the background of the slider. I would first try changing
'background-position': 'top left'
to:
'background-position': 'center center'
... actually, the entire script seems geared towards tiling the images. I'd imagine that's the technique it uses to generate some of its cool effects. This line is where it's centering the current image within the tile defined by sph and spw.
'background-position': -sLeft + 'px ' + (-sTop + 'px'),
and if you use spw=1 and sph=1 you can center it by changing that to a fixed 'center center'.
I don't really care for this script in terms of general purpose, but it seems to have worked well for the person who wrote it.
this is my hacky solution
<script>
$(window).load(function() {
$('#coin-slider').coinslider({
opacity: 0.6,
effect: "rain",
hoverPause: true,
dely: 3000
});
// center coin slider
setTimeout(function(){
centerCS();
},500);
});
// center coin slider image
function centerCS(){
var w=$(".container").width(); // container of coin slider
var csw=$("#coin-slider").width();
var lpad=(w-csw)/2;
$("#coin-slider").css("margin-left",lpad+"px");
}
</script>
Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?