I have a function that takes about 10 seconds to complete and it breaks if reactivated before the first iteration is completed - It acts as a text-fader - JQuery is not an option I want to use pure JS
My function:
//Text fading effect
function fadeText() {
var hex1 = 153,
hex2 = 204,
hex3 = 51;
function innerFade() {
if (hex1 >= 30) {
hex1 -= 1;
document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
}
if (hex2 >= 30) {
hex2 -= 1;
document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
}
if (hex3 >= 30) {
hex3 -= 1;
document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
}
setTimeout(innerFade, 20);
}
innerFade();
}
This is activated on button press, I want the first iteration to cancel or set the innerHTML of the div the text has been assigned to to innerHTML=""; if it is activated again before the animation is completed.
Big Edit:
//Set colour function
function setColor(elementName, r, g, b) {
document.getElementById(elementName).style.color = "rgb(" + r + "," + g + "," + b + ")";
}
//Text fading effect
var animationActive = false;
function fadeText() {
if (animationActive) return;
animationActive = true;
var hex1 = 153,
hex2 = 204,
hex3 = 51;
function innerFade() {
var rDone, gDone, bDone;
if (hex1 >= 30) {
hex1 -= 1;
setColor('confirmation', hex1, hex2, hex3);
} else {rDone = true;}
if (hex2 >= 30) {
hex2 -= 1;
setColor('confirmation', hex1, hex2, hex3);
} else {gDone = true;}
if (hex3 >= 30) {
hex3 -= 1;
setColor('confirmation', hex1, hex2, hex3);
} else {bDone = true;}
if (rDone && gDone && bDone) {
animationActive = false;
}
}
setTimeout(innerFade, 20);
}
You could disable the button to prevent calling the function again:
HTML:
<button onclick="fadeText(this)"> Fade text </button>
JavaScript:
function fadeText(btn) {
var elm = document.getElementById('confirmation'),
c = [153, 204, 51];
function loop() {
for (var i = 0; i < c.length; i++) {
if (c[i] >= 30) c[i] -= 1;
}
elm.style.color = 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] + ')';
return c[0] < 30 && c[1] < 30 && c[2] < 30 ?
btn.disabled = false : setTimeout(loop, 20);
}
btn.disabled = true;
loop();
}
Live demo: http://jsfiddle.net/nKV7A/
Related
This is what I have so far, I have the background set to a solid color and a div that when clicked generates the random color. I want it to be generated by the space bar, and I want it to output red 10% of the time. I am an amateur at JavaScript but am learning.
var r, g, b, cstring;
function colapply() {
color();
r = newcolor.slice(1, 3);
g = newcolor.slice(3, 5);
b = newcolor.slice(5, 7);
r = parseInt(r, 16);
g = parseInt(g, 16);
b = parseInt(b, 16);
cstring = "rgb(" + r + "," + g + "," + b + ")";
$(".colorc").html("<" + "div class=" + "'" + "colorc1" + "'" + ">" + "<" + "/" + "div" + ">" + newcolor + "<span class='rgb'>" + cstring + "</span>");
$("body").css({
"background": newcolor
});
$(".colorc").css({
"color": newcolor
});
$(".colorc1").css({
"background": cstring
});
}
var newcolor;
function color() {
newcolor = '#' + (Math.random().toFixed(6).toString(16)).slice(2);;
if (newcolor.length < 7) {
color();
}
}
$(".colorc").click(colapply);
colapply();
Try introducing a special case for red.
function color() {
if (Math.random() < 0.1) { // 10% of the time
newcolor = '#FF0000'
return;
}
newcolor = '#' + (Math.random().toFixed(6).toString(16)).slice(2);;
if (newcolor.length < 7) {
color();
}
}
I have the index.html file in that form fields are there form action is confirm.html. In confirm.html some data, I displayed using js. But showing the only table I decided to I use menus in that so more attractive for users. Whenever I'm trying to declare div(<h1>data</h1>) in confirm.html it won't be showing any data. so I decided to declare using js.
Top of the headers i have to show those menus:
document.write("<div class="Menu">");
document.write("<div class="leftmenu">");
document.write("<h4>Fegli</h4>");
document.write("<div class="Menu">");
doucment.write("<ul>");
document.write("<li>Home</li>");
document.write("</ul>");
document.write("</div>");
document.write("</div>");
document.write("</div>");
Confirm.html: code
<html>
<head>
<script type="text/javascript" src="calculate.js">
</script>
</head>
<body onload="init();">
<div id="Menu">
it wont showing on web page
</div>
</body>
</html>
Calculate.js code
// Called on body's `onload` event
var cumulative=0;
function init() {
var salary = parseInt(localStorage.getItem("salary"));
var percent = parseFloat(localStorage.getItem("percent"));
var age = parseInt(localStorage.getItem("age"));
var rAge = parseInt(localStorage.getItem("rAge"));
var sel = localStorage.getItem("sel");
var roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000); //Doing Rounding for basic column Display
var basic;
var factor = 0;
var biWeekly = 0, monthly = 0,annual = 0;
//Displaying Headers
document.write("<head>");
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"confirm.css\">");
document.write("<title>Result</title>");
document.write("</head>");
document.write("<body>");
/* document.write("<center>")
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
document.write("<h1>" + "FEGLI CALCULATIONS ON" + " " + today + "</h1>");
document.write("</center>")
*/
document.write("<table><tr><th> Age </th><th> Annual-Salary </th><th> BiWeekly-Premium </th><th> Monthly-Premium </th><th> Annual-Premium </th><th> Cumulative-Premium </th><th>Basic </th><th> Total </th></tr>");
basic = parseInt(roundedSalary * calculateFactor(age));
//document.write("roundedSalary"+roundedSalary+"calculateFactor"+calculateFactor(age));
premium = calculateBiweekly(salary, basic, age, rAge);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<tr><td>" + age + "/" + (age + 1) + "</td><td>" + "$" + salary.toFixed(2) + "</td><td>" + "$" + biWeekly.toFixed(2) + "</td><td>" + "$" + monthly.toFixed(2) + "</td><td>" + "$" + annual.toFixed(2) + "</td><td>" + "$" + cumulative.toFixed(2) + "</td><td>" + "$" + basic + "</td><td>-</td></tr>");
salary = parseFloat(salary);
for (var i = age + 1; i < 101; i++) {
document.write("<tr>");
document.write("<td>" + i + "/" + (i + 1) + "</td>");
if (i < rAge) {
salary = salary + (salary * percent);
roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000);
// document.write("age"+i+"roundedSalary"+roundedSalary+"<br>");
document.write("<td>" + "$" + salary.toFixed(2) + "</td>");
} else {
salary = 0;
document.write("<td>-</td>");
}
basic = parseInt(roundedSalary * calculateFactor(i));
premium = calculateBiweekly(salary, basic, i);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<td>" + "$" + biWeekly.toFixed(2) + "</td>");
document.write("<td>" + "$" + monthly.toFixed(2) + "</td>");
document.write("<td>" + "$" + annual.toFixed(2) + "</td>");
document.write("<td>" + "$" + cumulative.toFixed(2) + "</td>");
document.write("<td>" + "$" + basic + "</td>");
document.write("<td>-</td>");
document.write("</tr>");
}
document.write("</table>");
document.write("</body>")
}
function calculateFactor(age) {
var factor = 0;
if (age > 35 && age < 45) {
switch (age) {
case 36:
factor = 1.9;
break;
case 37:
factor = 1.8;
break;
case 38:
factor = 1.7;
break;
case 39:
factor = 1.6;
break;
case 40:
factor = 1.5;
break;
case 41:
factor = 1.4;
break;
case 42:
factor = 1.3;
break;
case 43:
factor = 1.2;
break;
case 44:
factor = 1.1;
break;
}
} else if (age <= 35) {
factor = 2;
} else if (age >= 45) {
factor = 1;
}
return factor;
}
function calculateBiweekly(salary, basic, age) {
var biWeekly = 0;
if (salary > 0) {
biWeekly = ((basic / calculateFactor(age)) * 0.15) / 1000;
monthly = ((basic / calculateFactor(age)) * 0.325) / 1000;
} else if (salary == 0 && age <= 65) {
biWeekly = ((basic / calculateFactor(age)) * (2.455 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.455)) / 1000;
} else if (salary == 0 && age > 65) {
//document.write("age"+age+"salary"+salary+"<br>");
biWeekly = ((basic / calculateFactor(age)) * (2.13 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.13)) / 1000;
}
annual = 12 * monthly;
cumulative = cumulative+annual;
//document.write("cumulative"+cumulative+"<br>");
return [biWeekly, monthly, annual, cumulative];
}// Called on body's `onload` event
I don't recommend document.write() to create element in DOM.
You need to use document.createElement() function to create new element using javascript.
function addMenu() {
var html = '<div class="Menu">';
html += '<div class="leftmenu">';
html += '<h4>Fegli</h4>';
html += '<div class="Menu">';
html += '<ul><li>Home</li></ul>';
html += '</div>';
html += '</div>';
html += '</div>';
document.getElementById("Menu").innerHTML = html;
}
addMenu();
<div id="Menu"></div>
In your code you applied table using document.write(), you can also create table tag using document.createElement() function. check below examples:
Example 1 :
function addTable() {
var c, r, t;
t = document.createElement('table');
t.border=1;
r = t.insertRow(0);//create row
c = r.insertCell(0);///create cell
c.innerHTML = "Apple";
c = r.insertCell(1);///create second cell
c.innerHTML = "Orange";
document.getElementById("mainContainer").appendChild(t);
}
addTable();
<div id="mainContainer"></div>
Example 2 :
function addTable() {
var html = "<table border='1'><tr><td>Apple</td><td>Orange</td></tr></table>";
document.getElementById("mainContainer").innerHTML = html;
}
addTable();
<div id="mainContainer"></div>
Both example will give same result.
To see the problem click on https://jsfiddle.net/kjz1myL2/16/ and when the fade is complete move your mouse from button to button REALLY FAST.
Is there a way to prevent events from crashing or reset them when they crash? I made a JavaScript event that happens with setInterval. This helps work the fades. It is a very crucial part of the code, but it crashes SUPER EASILY! If a user switches between two elements too fast, it will crash the setInterval. I wanted to make a mouse pause event in which it stops the user's mouse or a mouse slow event that slows the mouse speed to the slowest possible speed until the setInterval is over, but people have stated that taking the control from the user is VERY DANGEROUS for VERY OBVIOUS REASONS. Not exploring that option, I decided to come here and ask for a more user-friendly solution to prevent the crash from happening. I have this code (PART OF THE CODE) [ADJUSTED]:
JavaScript
window.addEventListener("load", TourFunction);
var TourFadeInEvent;
var TourYesMouseEnterTimeEvent, TourNoMouseEnterTimeEvent;
var TourYesMouseEnterEvent, TourNoMouseEnterEvent;
var TourYesMouseLeaveEvent, TourNoMouseLeaveEvent;
Steps = 3;
TourFunction()
function TourFunction(){
if (Steps == 3){
Opacity = 0;
TourFadeInEvent = window.setInterval(TourFadeIn, 20);
}else{
TourYesMouseEnterEvent = TourInputYes.addEventListener("mouseenter", TourYesMouseEnter);
TourNoMouseEnterEvent = TourInputNo.addEventListener("mouseenter", TourNoMouseEnter);
}
function TourFadeIn(){
if (Opacity <= 0 || Opacity < 1){
Opacity = Opacity + .01;
TourContainer.style.opacity = Opacity;
}else{
clearInterval(TourFadeInEvent);
Steps += 1;
TourFunction();
return Steps;
}
}
function TourYesMouseEnter(){
TourYesMouseEnterTimeEvent = window.setInterval(TourYesMouseEnterTime, 10);
function TourYesMouseEnterTime(){
if (YesfgcR < 255){
YesfgcR += 5;
YesfgColor = "rgb(" + YesfgcR + ", " + YesfgcG + ", " + YesfgcB + ")";
TourInputYes.style.color = YesfgColor;
}if (YesbcR < 255){
YesbcR += 5;
YesbColor = "rgb(" + YesbcR + ", " + YesbcG + ", " + YesbcB + ")";
TourInputYes.style.borderColor = YesbColor;
}if (NofgcR > 0){
NofgcR = 0;
NofgColor = "rgb(" + NofgcR + ", " + NofgcG + ", " + NofgcB + ")";
TourInputNo.style.color = NofgColor;
}if (NobcR > 0){
NobcR = 0;
NobColor = "rgb(" + NobcR + ", " + NobcG + ", " + NobcB + ")";
TourInputNo.style.borderColor = NobColor;
}if (YesfgcR >= 255 && YesbcR >= 255 && NofgcR == 0 && NobcR == 0){
clearInterval(TourYesMouseEnterTimeEvent);
return YesfgcR, YesbcR, YesfgColor, YesbColor;
}
}
}
function TourNoMouseEnter(){
TourNoMouseEnterTimeEvent = window.setInterval(TourNoMouseEnterTime, 10);
function TourNoMouseEnterTime(){
if (NofgcR < 255){
NofgcR += 5;
NofgColor = "rgb(" + NofgcR + ", " + NofgcG + ", " + NofgcB + ")";
TourInputNo.style.color = NofgColor;
}if (NobcR < 255){
NobcR += 5;
NobColor = "rgb(" + NobcR + ", " + NobcG + ", " + NobcB + ")";
TourInputNo.style.borderColor = NobColor;
}if (YesfgcR > 0){
YesfgcR = 0;
YesfgColor = "rgb(" + YesfgcR + ", " + YesfgcG + ", " + YesfgcB + ")";
TourInputYes.style.color = YesfgColor;
}if (YesbcR > 0){
YesbcR = 0;
YesbColor = "rgb(" + YesbcR + ", " + YesbcG + ", " + YesbcB + ")";
TourInputYes.style.borderColor = YesbColor;
}if (NofgcR >= 255 && NobcR >= 255 && YesfgcR == 0 && YesbcR == 0){
clearInterval(TourNoMouseEnterTimeEvent);
return NofgcR, NobcR, NofgColor, NobColor;
}
}
}
}
The code runs fine if you don't switch from each button too fast but if you go to fast, it will crash. I have been experiencing this a lot and have not gotten an answer. PLEASE give me something to work off of.
Use CSS transitions for the color fade instead -
document.getElementById('Game1_TourInputYes').addEventListener('mouseover', switchActive);
document.getElementById('Game1_TourInputNo').addEventListener('mouseover', switchActive);
function switchActive(e) {
var others = document.getElementsByClassName('btn-tour-input');
for (let i = 0; i < others.length; i++) {
others[i].classList.remove('active');
}
this.classList.add('active');
}
input[type=button] {
background: transparent;
border: 3px solid black;
color: black;
transition: all .4s ease-in-out;
padding: 10px 30px;
}
input.active {
border: 3px solid red;
color: red;
}
<input class="btn-tour-input Tour_Input_Yes" id="Game1_TourInputYes" type="button" value="Yes" />
<input class="btn-tour-input Tour_Input_No" id="Game1_TourInputNo" type="button" value="No" />
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>
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>