Fiddle: https://jsfiddle.net/fLfg7yqn/
JQuery:
$(function () {
$('.dvContentSlide').not(':eq(0)').addClass("dispNone");
$('.dvContentSlide:eq(0)').addClass("slideIsActive");
var g = parseInt($('div.slideIsActive').index()) + 1;
var u = $(".dvContentSlide").length;
$("#spCur").text("Current Index: " + g);
$("#spDVLen").text("SLIDE div length: " + $(".dvContentSlide").length);
for (var i = 0; i < u; i++)
$(".ulContentSliderNav").append('<li><span></span></li>');
$(".ulContentSliderNav :first-child a").addClass("ulContentSliderNavSel");
$(".cSlider").mouseover(function () {
clearInterval(po);
}).mouseout(function () {
po = setInterval(AutoSlide, 4000);
});
$(".ulContentSliderNav a").click(function (e) {
e.preventDefault();
$(this).parent().parent().find(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(this).addClass("ulContentSliderNavSel");
GoToTheSlide($(this).parent().index());
});
function GoToTheSlide(t) {
$('.dvContentSlide').addClass("dispNone");
$('.dvContentSlide').removeClass("slideIsActive");
$('.dvContentSlide:nth-child(' + ++t + ')').addClass("slideIsActive").removeClass("dispNone");
}
$("#aContentSliderNext").click(function () {
var k = $('div.slideIsActive').index() + 1;
if (k >= $(".dvContentSlide").length) {
k = 1;
$('.dvContentSlide').not(':eq(0)').addClass("dispNone").removeClass("slideIsActive");
$('.dvContentSlide:eq(0)').addClass("slideIsActive").removeClass("dispNone");
}
else {
$(".dvContentSlide:nth-child(" + k + ")").removeClass("slideIsActive").addClass("dispNone");
$(".dvContentSlide:nth-child(" + ++k + ")").removeClass("dispNone").addClass("slideIsActive");
}
$("#spCur").text("Current Index: " + k);
$(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(".ulContentSliderNav li:nth-child(" + k + ") a").addClass("ulContentSliderNavSel");
});
$("#aContentSliderPrev").click(function () {
var k = $('div.slideIsActive').index() + 1;
if (k <= 1) {
k = $(".dvContentSlide").length;
$('.dvContentSlide').not(':eq(' + k + ')').addClass("dispNone").removeClass("slideIsActive");
$('.dvContentSlide:nth-child(' + k + ')').addClass("slideIsActive").removeClass("dispNone");
}
else {
$(".dvContentSlide:nth-child(" + k + ")").removeClass("slideIsActive").addClass("dispNone");
$(".dvContentSlide:nth-child(" + --k + ")").removeClass("dispNone").addClass("slideIsActive");
}
$("#spCur").text("Current Index: " + k);
$(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(".ulContentSliderNav li:nth-child(" + k + ") a").addClass("ulContentSliderNavSel");
});
function AutoSlide() {
var k = $('div.slideIsActive').index() + 1;
console.log(k);
if (k >= $(".dvContentSlide").length) {
k = 1;
$('.dvContentSlide').not(':eq(0)').addClass("dispNone").removeClass("slideIsActive");
$('.dvContentSlide:eq(0)').addClass("slideIsActive").removeClass("dispNone");
}
else {
$(".dvContentSlide:nth-child(" + k + ")").removeClass("slideIsActive").addClass("dispNone");
$(".dvContentSlide:nth-child(" + ++k + ")").removeClass("dispNone").addClass("slideIsActive");
}
$("#spCur").text("Current Index: " + k);
$(".ulContentSliderNavSel").removeClass("ulContentSliderNavSel");
$(".ulContentSliderNav li:nth-child(" + k + ") a").addClass("ulContentSliderNavSel");
}
var po = setInterval(AutoSlide, 4000);
});
Everything is working fine except how can I update the jquery/css so instead of showing the slide, it fades out the current slide and fades in the next slide with keeping the structure as is.
Have you tried fadeOut() fadeIn()? I didn't see it in your code, follow this link to see if it will meet your need.
Related
I have a function (selectWord ()) that collects selected words, which calls a function (view (word [i])) by passing each word through a loop.
selectWord():
$('#button').on('click', function() {
var text = "";
var lang = $("#lang").text();
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var word = text.split(" ");
$('#load').html("");
var promises = [];
for (var i = 0; i < word.length; i++) {
promises.push(Promise.resolve(view(word[i], lang)));
}
Promise.all(promises).catch(function(err) {
console.log("error");
return err;
}).then(function() {
$.each(promises, function(key, val) {
$.each(val, function(k, v) {
console.log("promises " + k + " " + v + " " + v[k] + '<br>');
$('#div').append("promises " + k + " " + v + " " + v[k] + '<br>');
});
});
});
}
});
view():
function view(word, lang) {
var html = "";
var id = "";
img = "";
ids = [];
fullLemmas = [];
gramCats = [];
setTimeout(wiki(word, lang), 1000);
setTimeout(function() {
for (var i = 0; i < ids.length; ++i) {
if (i == 0) {
getImg(ids[i], word);
wiki = fullLemmas[i];
gramCategory = gramCats[i];
}
}
}, 2000);
setTimeout(function() {
for (var i = 0; i < ids.length; ++i) {
if (i == 0) {
id = ids[i];
html += '<li class="col-12 col-md-6 col-lg-3"><div class="cnt-block equal-hight" style="height: 349px;"><figure><img id ="' + id + '" src="' + img + '" class="img-responsive" alt=""></figure><h3>"' + word + ' (' + gramCats[i] + ')' + '"</h3>';
}
html += '<p>' + fullLemmas[i] + ' (' + gramCats[i] + ')</p>';
}
html += '</li>';
return html;
}, 3000);
}
The view function in turn calls two functions that run through a JSON with getJSON (), the problem is synchrony. I have used setTimeOut () and Promises but I do not understand what it returns.
When showing the words, it keeps only the data of the last word.
I want to solve Bliffoscope Data Analysis Problem using javascript. I have following question.
This is SlimeTorpedo
+
+
+++
+++++++
++ ++
++ + ++
++ +++ ++
++ + ++
++ ++
+++++++
+++
This is TestData
+ + + ++ + +++ + +
+ ++ + + ++++ + + + + + + +++ +++ +
+ + + ++ ++ ++ + ++ + + + + +
+ ++ + ++ + + + ++ ++ + +
++++++ + + + ++ + + + + ++ + + +
+ + + + + ++ + ++ + + + +
+++ + ++ + + + +++ + + ++ +
+++++ + + + + + + + +
+ + + + + + + + + + + +
++ + + + ++ + + + ++
There is one question already similar to this but in Java. This question is asked here.
How can I solve this in JavaScript.
UPDATE
I tried following solution.
const fs = require('fs');
let torpedo = [], starship = [], testData = [];
// counter = -1;
function getTorpedoData(fileName, type) {
let counter = -1;
return new Promise(function(resolve, reject) {
fs.readFile(fileName,'utf8', (err, data) => {
if (err) {
reject();
} else {
for (let i = 0; i < data.length; i++) {
if (data[i] == '\n' || counter === -1) {
torpedo.push([]);
counter++;
} else {
torpedo[counter].push(data[i]);
}
}
}
console.log(data);
resolve();
});
});
}
function getTestData(fileName, type) {
let counter = -1;
return new Promise(function(resolve, reject) {
fs.readFile(fileName,'utf8', (err, data) => {
if (err) {
reject();
} else {
for (let i = 0; i < data.length; i++) {
if (data[i] == '\n' || counter === -1) {
testData.push([]);
counter++;
} else {
testData[counter].push(data[i]);
}
}
}
console.log(data);
resolve();
});
});
}
let score = 0;
getTorpedoData('./SlimeTorpedo.blf', 'torpedo').then((data) => {
getTestData('./TestData.blf', 'testData').then(() => {
torpedo.forEach((torpedoArray, torpedoIndex) => {
torpedoArray.filter((contents) => {
if (contents === '+') {
testData.forEach((testDataArray) => {
testDataArray.filter((dataContents, dataIndex) => {
// console.log(dataContents);
if (dataContents === '+') {
if (torpedoIndex === dataIndex) {
score++;
}
// console.log(score);
}
});
});
}
});
});
});
});
I creating 3 arrays torpedo, starship and testData. I read all these files and put them in multidimensional array(above). Then I am trying to find compare the indexes if torpedo array in testData array. However, there is something I am doing wrong. How can I fix it?
[Edit by Spektre]
Test results for test data (both this and the one from #greybeard link):
Red mean mismatch and Yellow mean match. Score is incremented for match and decremented for mismatch. x counts from zero to rightwards and y counts from zero downwards but your data was enlarged by empty line so you can count from 1 instead ...
Are you looking for something like this (Fiddle)?
// Create our images: torpedo (object) and background (context)
var object = " +\n +\n +++\n +++++++\n ++ ++\n++ + ++\n++ +++ ++\n++ + ++\n ++ ++\n +++++++\n +++",
context = " + + + ++ + +++ + +\n + ++ + + ++++ + + + + + + +++ +++ +\n + + + ++ ++ ++ + ++ + + + + +\n+ ++ + ++ + + + ++ ++ + +\n ++++++ + + + ++ + + + + ++ + + +\n + + + + + ++ + ++ + + + +\n+++ + ++ + + + +++ + + ++ +\n +++++ + + + + + + + +\n + + + + + + + + + + + +\n ++ + + + ++ + + + ++ ";
var c = document.getElementById("test_canvas"),
ctx = c.getContext("2d"),
scale = 10;
// Draw a pixel on canvas
function draw_pixel(x, y, fill_style) {
ctx.fillStyle = fill_style;
ctx.fillRect(x * scale, y * scale, scale, scale);
}
// Receive an array of coordinates, draw pixels
function draw_image(serialized_image, fill_style) {
for (var i = 0, len = serialized_image.length; i < len; i++) {
draw_pixel(serialized_image[i][0], serialized_image[i][1], fill_style);
}
}
// Receive a text string, turn it into an array of coordinates of filled in pixels
function serialize_map(char_map) {
var x = 0,
y = 0,
c,
map = [];
for (var i = 0, len = char_map.length; i < len; i++) {
c = char_map[i];
if (c == '+') {
map.push([x, y])
}
x += 1;
if (c == '\n') {
x = 0;
y += 1;
}
}
return map;
}
// Find number of intersections between two images
function array_intersect() {
var a, d, b, e, h = [],
f = {},
g;
g = arguments.length - 1;
b = arguments[0].length;
for (a = d = 0; a <= g; a++) {
e = arguments[a].length, e < b && (d = a, b = e);
}
for (a = 0; a <= g; a++) {
e = a === d ? 0 : a || d;
b = arguments[e].length;
for (var l = 0; l < b; l++) {
var k = arguments[e][l];
f[k] === a - 1 ? a === g ? (h.push(k), f[k] = 0) : f[k] = a : 0 === a && (f[k] = 0);
}
}
return h;
}
// Translate the coordinates of a serialized image
function translate(coords, ix, iy) {
return [coords[0] + ix, coords[1] + iy];
}
// Find in which position the object has more intersections with the background
function get_best_position(context, object) {
// Calculate image dimensions
context_width = context.sort(function(a, b) {
return b[0] - a[0];
})[0][0];
context_height = context.sort(function(a, b) {
return b[1] - a[1];
})[0][1];
object_width = object.sort(function(a, b) {
return b[0] - a[0];
})[0][0];
object_height = object.sort(function(a, b) {
return b[1] - a[1];
})[0][1];
// Swipe context, store amount of matches for each patch position
similaritudes = [];
for (var cx = 0; cx < context_width; cx++) {
for (var cy = 0; cy < context_height; cy++) {
translated_object = object.map(function(coords) {
return translate(coords, cx, cy);
})
intersection = array_intersect(context, translated_object);
// console.log(translated_object);
similaritudes[intersection.length] = [cx, cy];
}
}
// Return position for which number of matches was greater
return similaritudes.slice(-1)[0];
}
// Parse our images from the text strings
var serialized_context = serialize_map(context);
var serialized_object = serialize_map(object);
// Find best position for our torpedo
var best_position = get_best_position(serialized_context, serialized_object);
// Translate torpedo to best position
positioned_object = serialized_object.map(function(coords) {
return translate(coords, best_position[0], best_position[1]);
});
// Draw background and torpedo
draw_image(serialized_context, "gray");
draw_image(positioned_object, "rgba(0, 255, 0, 0.5)");
<canvas id="test_canvas" width="800" height="120" style="border:1px solid #000000;">
</canvas>
UPDATE:
I changed my script to this and it works. Way simpler and it works.
function myFunction(valor) {
var elementos = document.getElementsByClassName("inner");
var i;
for (i = 1; i < elementos.length+1; i++) {
document.getElementById("age"+i).style.visibility = "hidden";
}
document.getElementById("age"+valor).style.visibility = "visible";
}
I have this script:
function myFunction(valor) {
alert("Has seleccionado " + valor);
var elementos = document.getElementsByClassName("inner");
//alert ("Tienes " + elementos.length + " elementos.");
var i;
for (i = 1; i < elementos.length + 1; i++) {
var sty = document.getElementById("age" + i);
//alert("age"+i);
if (getComputedStyle(sty).getPropertyValue("visibility") == "hidden") {
document.getElementById("age" + valor).style.visibility = "visible";
} else {
document.getElementById("age" + i).style.visibility = "hidden";
}
}
}
That I control with a slider control. What I'm doing is hiding or showing some divs with depending of what I choose from the slider.
This is how I paint my data before trying to hide or shsow elements with the slider:
$(window).load(function() {
$.getJSON('http://xxxxx/xxxxx.json', function(data) {
var output = "<ul class='lista'><div class='outer'>";
for (var i in data.lbclassic) {
output += "<div style='visibility:hidden;' class='inner'id=" + "age" + data.lbclassic[i].ageinweeks + ">" + "<p>" + data.lbclassic[i].ageinweeks + "--" + data.lbclassic[i].cumul + "--" + data.lbclassic[i].perhh + "--" + data.lbclassic[i].perhd + "--" + data.lbclassic[i].eggweightinweek + "--" + data.lbclassic[i].eggmasscumul1 + "--" + data.lbclassic[i].eggmassinweek + "--" + data.lbclassic[i].eggmasscumul + "</p></div>";
}
output += "</div></ul>";
document.getElementById("placeholder").innerHTML = output;
});
});
This works great until one point - once I get to the last element (90 in this case), it won't show up.
Isn't it more easy to use the css "display:none;" feature for hidding your element.
.yourclass{
display:none;
}
just edit the class with js
Link to CSS
function myFunction(valor) {
var elementos = document.getElementsByClassName("inner");
var i;
for (i = 1; i < elementos.length+1; i++) {
document.getElementById("age"+i).style.visibility = "hidden";
}
document.getElementById("age"+valor).style.visibility = "visible";
}
this is my click function
$('.cal table tbody td').on('click', function () {
if($(this).hasClass('available'))
{
alert('asd');
}
});
the problem i am having is that after i have switched to the next or previous month, my clicking function on the calendar does not work.
For example in my JSFIDDLE, if u move to the previous month and then move back to the current month and do the click function, it wouldn't work anymore.
EDIT: I'm using an external library called date.js, check out my jsfiddle for a clearer idea of what is going on.
EDIT 2: updated jsfiddle link
jsfiddle
Use this
$(document).on('click','.cal table tbody td', function () {
if ($(this).hasClass('available')) {
alert('asd');
}
});
instead of this
$('.cal table tbody td').on('click', function () {
if ($(this).hasClass('available')) {
alert('asd');
}
});
Former is the correct replacement for delegate
one thing I notice immediately is that when you do things like:
$('#calendar tbody').append('<tr id = row'+i+'></tr>');
you need to remember that when you want to give an ID to an element the 'value' portion of the ID should be enclosed in quotations.
So you need to escape the string to include them so your browser can interpret the html properly.
ie
$('#calendar tbody').append('<tr id = \"row'+i+'\"></tr>');
that way your output looks like:
<tr id="rowx"></tr>
instead of:
<tr id=rowx></tr>
Your previous and next event handlers are recreating the DOM elements used for rendering the calendar. However, your click handler is only only attached to the elements that exist in the DOM at the time that handler is registered. The documentation of on() states:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on()
You'll probably need to re-register that click handler as part of your calendarInit() function after the new rows in the calendar - the new elements - have been rendered.
You may view a working version here. Or take a look at the updated jQuery below.
var firstday = new Date();
var lastday = new Date();
var calendarmonth = new Date();
var CCheck;
$(document).ready(function () {
Date.today();
firstday.setMonth(Date.today().getMonth(), 1);
lastday.setMonth(Date.today().getMonth() + 1, 0);
calendarmonth.setMonth(Date.today().getMonth());
calendarInit();
$('#calendar-prev').on('click', function () {
if (CCheck > 35) {
//render 6 rows
for (i = 1; i < 7; i++) {
$('#row' + i).remove();
}
} else {
//render 5 rows
for (i = 1; i < 6; i++) {
$('#row' + i).remove();
}
}
$("#month").empty();
calendarmonth.addMonths(-1);
firstday.addMonths(-1);
lastday.setMonth(firstday.getMonth() + 1, 0);
calendarInit();
});
$('#calendar-next').on('click', function () {
if (CCheck > 35) {
//render 6 rows
for (i = 1; i < 7; i++) {
$('#row' + i).remove();
}
} else {
//render 5 rows
for (i = 1; i < 6; i++) {
$('#row' + i).remove();
}
}
$("#month").empty();
calendarmonth.addMonths(1);
firstday.addMonths(1);
lastday.setMonth(firstday.getMonth() + 1, 0);
calendarInit();
});
addRemoveClickTrigger();
});
function calendarInit() {
CCheck = lastday.getDate() + firstday.getDay();
var i;
var colNo;
var a = 1;
var days = new Array();
$("#month").append("Month: " + calendarmonth.toString("MMMM, yyyy"));
if (CCheck > 35) {
//render 6 rows
for (i = 1; i < 7; i++) {
$('#calendar tbody').append('<tr id = row' + i + '></tr>');
colNo = a + 6;
for (a; a <= colNo; a++) {
var datenum = a - firstday.getDay();
if (datenum < 1) {
$('#row' + i).append('<td></td>');
} else if (datenum > lastday.getDate()) {
$('#row' + i).append('<td></td>');
} else {
$('#row' + i).append('<td id = Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + datenum + '>' + datenum + '</td>');
days[datenum] = new Date();
days[datenum].set({
month: calendarmonth.getMonth(),
day: datenum,
year: calendarmonth.getFullYear()
});
}
}
}
} else {
//render 5 rows
for (i = 1; i < 6; i++) {
$('#calendar tbody').append('<tr id = row' + i + '></tr>');
colNo = a + 6;
for (a; a <= colNo; a++) {
var datenum = a - firstday.getDay();
if (datenum < 1) {
$('#row' + i).append('<td></td>');
} else if (datenum > lastday.getDate()) {
$('#row' + i).append('<td></td>');
} else {
$('#row' + i).append('<td id = Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + datenum + '>' + datenum + '</td>');
days[datenum] = new Date();
days[datenum].set({
month: calendarmonth.getMonth(),
day: datenum,
year: calendarmonth.getFullYear()
});
}
}
}
}
/*alert(Date.today().getMonth());
alert(calendarmonth.getMonth());*/
if (Date.today().getMonth() == calendarmonth.getMonth() && Date.today().getFullYear() == calendarmonth.getFullYear()) {
for (i = 1; i <= lastday.getDate(); i++) //Date highlight
{
if (Date.today().getDate() == i) //highlight today's date
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("today");
} else if (Date.today().getDate() > i) //highlight unavailable dates
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("unavailable");
} else if (Date.today().getDate() < i) {
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("available");
}
}
} else if (Date.today() > calendarmonth) {
for (i = 1; i <= lastday.getDate(); i++) //Highlight dates before today to unavailable
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("unavailable");
}
} else {
for (i = 1; i <= lastday.getDate(); i++) //Condition highlighting
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("available");
if (days[i].getDay() == 0 || days[i].getDay() == 6) // set weekends to unavailable
{
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).removeClass("available");
$('#Y' + calendarmonth.getFullYear() + 'M' + calendarmonth.getMonth() + 'Day' + i).addClass("unavailable");
}
}
}
addRemoveClickTrigger();
} //calendarInit()
function addRemoveClickTrigger()
{
$('.cal table tbody td').off();
$('.cal table tbody td').on({
'click':
function ()
{
alert(jQuery(this).prop('class'));
if ($(this).hasClass('available'))
{
alert('asd');
}
}
});
} //addRemoveClickTrigger()
I hope this helps.
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>