How to get background to shuffle between images? - javascript

I have an HTML webpage with the background shuffling through the images using javascript that are listed within an array. I was wondering if it would be possible to shuffle between these images in a random order every time the webpage is loaded. There are currently about 61 images that are within the array all named 1.jpg, 2.jpg, 3.jpg within the pics folder. I would really like this to be updateable if we add/remove images in the future.
For example, one time it will be 3,2,1,5,3, the next it will 1,3,2,5,4, next 5,1,4,2,3 and so on. Complete randomness.
Here is my HTML and Javascript
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<script src="jquery.js"></script>
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</head>
<body>
</div>
<div id="carbon-block"></div>
</div>
</div>
<script src="jquery-background-slideshow.js"></script>
<script>
$(document).ready(function() {
/*
$(".layer").backgroundSlideshow({
delay: 3000,
transitionDuration: 3000,
images: [
"assets/images/image3.jpeg",
"assets/images/image4.jpeg"
]
})
*/
$("body").backgroundSlideshow({
onBeforeTransition: function(index) {
console.log("before transition", index)
},
onAfterTransition: function(index) {
console.log("after transition", index)
},
transitionDuration: 3000,
fixed: true,
images: ["pics/1.jpg", "pics/2.jpg", "pics/3.jpg", "pics/4.jpg"]
})
})
</script>
</body>
</html>
And here is there "jquery-background-slideshow.js"
* Author and copyright: Stefan Haack (https://shaack.com)
* Repository: https://github.com/shaack/jquery-background-slideshow/
* License: MIT, see file 'LICENSE'
*/
;(function ($) {
"use strict"
$.fn.backgroundSlideshow = function (options) {
this.each(function () {
var $container = $(this)
var $currentLayer = null
var $nextLayer = null
var currentImageIndex = 0
var nextImageIndex = 0
var preloadedImages = []
var config = {
delay: 5000,
transitionDuration: 3000,
onBeforeTransition: null,
onAfterTransition: null,
fixed: false,
images: []
}
for (var option in options) {
config[option] = options[option]
}
var transition = "opacity " + config.transitionDuration + "ms ease-in-out"
var layerStyles = {
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
backgroundPosition: "center center",
position: config.fixed ? "fixed" : "absolute",
left: 0,
right: 0,
bottom: 0,
top: 0,
zIndex: -1
}
var layerStylesTransition = {
transition: transition,
"-webkit-transition": transition,
"-moz-transition": transition,
"-o-transition": transition
}
function preLoadImage(index) {
if (!preloadedImages[index]) {
preloadedImages[index] = new Image()
preloadedImages[index].src = config.images[index]
}
}
function addLayer(imageSrc, withTransition) {
var $newLayer = $("<div class='backgroundSlideshowLayer'/>")
var thisLayerStyles = layerStyles
thisLayerStyles.backgroundImage = "url(" + imageSrc + ")"
$newLayer.css("opacity", "0")
$newLayer.css(thisLayerStyles)
if(withTransition) {
$newLayer.css(layerStylesTransition)
}
var $lastLayer = $container.find("> .backgroundSlideshowLayer").last()
if ($lastLayer[0]) {
$lastLayer.after($newLayer)
} else {
$container.prepend($newLayer)
}
return $newLayer
}
function nextImage(withTransition) {
currentImageIndex = nextImageIndex
nextImageIndex++
if (nextImageIndex >= config.images.length) {
nextImageIndex = 0
}
if ($nextLayer) {
$currentLayer = $nextLayer
} else {
$currentLayer = addLayer(config.images[currentImageIndex], withTransition)
}
if (config.onBeforeTransition) {
config.onBeforeTransition(currentImageIndex)
}
$currentLayer.css("opacity", "1")
setTimeout(function() {
if (config.onAfterTransition) {
config.onAfterTransition(currentImageIndex)
}
preLoadImage(nextImageIndex)
}, withTransition ? config.transitionDuration : 0)
setTimeout(function() {
$nextLayer = addLayer(config.images[nextImageIndex], true)
cleanUp()
}, config.transitionDuration)
}
function cleanUp() {
var $layers = $container.find("> .backgroundSlideshowLayer")
if ($layers.length > 2) {
$layers.first().remove()
}
}
$container.css("position", "relative")
nextImage(false)
setTimeout(function () {
nextImage(true)
setInterval(function () {
nextImage(true)
}, config.delay + config.transitionDuration)
}, config.delay)
})
}
}(jQuery)) ```

I would create an empty array and push all of my images in a random order and use the new array for display.
let randomImageOrder = [];
let imageArray = ['pics/1.jpg','pics/2.jpg','pics/3.jpg','pics/4.jpg','pics/5.jpg'];
while(imageArray.length > 0) {
let randomIndex = Math.floor(Math.random()*imageArray.length);
randomImageOrder.push(imageArray[Math.floor(Math.random()*imageArray.length)]);
imageArray.splice(randomIndex, 1);
}
console.log(randomImageOrder);

Related

Javascript. Delayed div creation with

I'm trying to delay creation of each div by 1 sec to no avail, Can't figure out how to use setTimeout or setInterval, any help appreciated.
(also, would like to position divs centered relative to each other).
I'm trying to draw series of them of decreasing sizes, in each other.
Any advice appreciated
var i;
var w = 400;
var delay = 3000;
$(function () {
$("#boom").click(function () {
for (w, i = 0; w >= 20; i++, w = w - 20) {
$('body').append('<div id="div' + i + '" />'); {
if (i % 2 === 0) {
$("#div" + i + "").css({
"background-color": "gold",
"position": "absolute",
"z-index": i,
"top": "20vw",
"left": "20vw",
}).width(w).height(w);
} else {
$("#div" + i + "").css({
"background-color": "chartreuse",
"position": "absolute",
"z-index": i,
"top": "20vw",
"left": "20vw",
}).width(w).height(w);
}
}
}
});
});
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Kwadrat w kwadracie</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="boom">Vamos!</button>
<div id="outer"></div>
</body>
</html>
I'm not sure if I exactly understood what is your desired result, but I think this is what you are trying to achieve:
const outerDiv = document.getElementById('outer'),
sizeDecrement = 20;
document.getElementById('boom').addEventListener('click', event => {
let lastDiv = outerDiv,
size = 400;
const interval = setInterval(() => {
const div = document.createElement('div');
div.className = 'inner ' + (size % (2 * sizeDecrement) === 0 ? 'even' : 'odd');
[div.style.height, div.style.width] = [size + 'px', size + 'px'];
lastDiv.append(div);
lastDiv = div;
size -= sizeDecrement;
if (size < sizeDecrement) {
clearInterval(interval);
}
}, 500);
});
.inner {
align-items: center;
display: flex;
justify-content: center;
}
.inner.odd {
background-color: chartreuse;
}
.inner.even {
background-color: gold;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Kwadrat w kwadracie</title>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="boom">Vamos!</button>
<div id="outer"></div>
</body>
</html>
Also, regarding your code: $(function () { is unnecessary, and so is using such an amount of per-div styling instead of creating a class and giving it those styles in style sheet.
See following snippet. I hope it will help
var i = 0;
var w = 400;
var delay = 500;
$(function () {
$("#boom").click(myLoop);
});
function myLoop () {
setTimeout(function () {
$( i === 0 ? 'body' : '#div'+(i-1)).append('<div id="div' + i + '" />');
$("#div" + i + "").css({
"background-color": i % 2 === 0 ? "gold" : "chartreuse",
"position": "relative",
"z-index": i,
"top": i === 0 ? "20vw": "10px",
"left": i === 0 ? "20vw": "10px",
}).width(w).height(w);
i++;
w = w - 20
if (w >= 20) {
myLoop();
}
}, delay)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="boom">Vamos!</button>
<div id="outer"></div>
See fiddle also

How to append result to Geocoder text box using arcgis javascript api?

I want to append result of a custom search in a Geocoder text box in arcgis javascript api by over ridding the default result.
I have written below code for that but i am not getting satisfactory result.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Geocoder</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<style>
html, body, #map
{
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#search
{
display: block;
position: absolute;
z-index: 3;
top: 20px;
left: 75px;
}
.spotlight
{
z-index: -1;
position: absolute;
left: 50%;
top: 50%;
border-radius: 50%;
opacity: 0;
box-shadow: inset rgba(0,0,0,0.25) 0px 0px 20px 20px, rgba(0,0,0,0.25) 0px 0px 0px 1000px;
transition: all 1000ms;
-moz-transition: all 1000ms;
-webkit-transition: all 1000ms;
}
.spotlight-active
{
z-index: 2;
opacity: 1;
}
</style>
<script src="http://js.arcgis.com/3.11/"></script>
<script type="text/javascript">
require([
"esri/map",
"esri/dijit/Geocoder",
"esri/graphic",
"esri/symbols/SimpleMarkerSymbol",
"esri/geometry/screenUtils",
"dojo/dom",
"dojo/dom-construct",
"dojo/query",
"dojo/_base/Color",
"esri/tasks/locator",
"esri/geometry/Polygon",
"dojo/_base/array",
"dojo/domReady!"
], function (
Map, Geocoder,
Graphic, SimpleMarkerSymbol, screenUtils,
dom, domConstruct, query, Color, Locator, Polygon, arrayUtils
) {
var _RLCCspatialReference = new esri.SpatialReference({ "wkt": 'classified' });
//var _RMapsExt = new esri.geometry.Extent(-4086033.961945721, -806460.9357572012, 3756052.906228016, 5050597.693910059, _RLCCspatialReference);
var _RMapsExt = new esri.geometry.Extent(-2498256.744659858, 887180.8538370342, 2243086.071359108, 4139445.6917000436, _RLCCspatialReference);
// create a map and instance of the geocoder widget here
var map = new esri.Map("map", { logo: false, nav: false, wrapAround180: true });
map.spatialReference = _RLCCspatialReference;
map.fullExtent = _RMapsExt;
map.initialExtent = _RMapsExt;
var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://xxxx.rxx.com/arcgis/rest/services/Rmaps_Updated/MapServer");
map.addLayer(tiledMapServiceLayer);
map.setScale(14000000);
map.setExtent(_RMapsExt, true);
var gc = [{
url: "http://11.66.22.33:6080/arcgis/rest/services/Locator_Comb_Prd/GeocodeServer",
name: "Locator_Comb_Prd",
singleLineFieldName: "SingleLine"
}];
var geocoder = new Geocoder({
map: map,
arcgisGeocoder: false,
geocoders: gc,
autoNavigate: false,
autoComplete: true,
showResults: true,
geocoders: gc,
geocoderMenu: false,
}, dom.byId("search"));
//"search" dom.byId("search")
geocoder.startup();
geocoder.on("select", showLocation);
geocoder.on("FindResults", showLocation);
dojo.connect(geocoder, 'onAutoComplete', function (results) {
$("#search_input").autocomplete({
source: function (request, response) {
$.support.cors = true;
$.ajax({
dataType: "json",
type: 'POST',
url: 'http://11.66.22.44/Geocoder/Query.aspx',
crossdomain: true,
timeout: 100000,
cache: true,
data: { RequestType: "AutoComplete", AutoCompleteValue: $("#search_input").val() },
success: function (data) {
//$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
if (data != null) {
response(data);
}
},
error: function (data) {
alert("error:" + data.statusText);
//$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3,
open: function () {
},
close: function () {
},
focus: function (event, ui) {
},
select: function (event, ui) {
}
});
//console.log('autocomplete', results);
});
function showLocation(evt) {
var point = null;
if (evt.result.feature.geometry.type == "point" && evt.result.feature.geometry.x != 0 && evt.result.feature.geometry.y != 0) {
point = evt.result.feature.geometry;
map.graphics.clear();
var symbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_SQUARE).setColor(new Color([255, 0, 0, 0.5]));
var graphic = new Graphic(point, symbol);
map.graphics.add(graphic);
map.infoWindow.setTitle("Search Result");
map.infoWindow.setContent(evt.result.name);
map.infoWindow.show(evt.result.feature.geometry);
}
else {
map.graphics.clear();
locator = new Locator("http://11.66.66.33:6080/arcgis/rest/services/Locator_Comb_Prd/GeocodeServer");
locator.on("address-to-locations-complete", showResults);
var address = {
"SingleLine": evt.result.name
};
var resultName = evt.result.name;
locator.outSpatialReference = map.spatialReference;
var options = {
address: address,
outFields: ["Loc_name"]
};
locator.addressToLocations(options);
function showResults(evt) {
var symbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_SQUARE).setColor(new Color([255, 0, 0, 0.5]));
var geom;
arrayUtils.every(evt.addresses, function (candidate) {
if (candidate.location.type == "point" && candidate.location.x != 0 && candidate.location.y != 0) {
console.log(candidate.score);
if (candidate.score > 80) {
console.log(candidate.location);
var attributes = {
address: candidate.address,
score: candidate.score,
locatorName: candidate.attributes.Loc_name
};
geom = candidate.location;
point = geom;
var graphic = new Graphic(point, symbol);
//add a graphic to the map at the geocoded location
map.graphics.add(graphic);
//add a text symbol to the map listing the location of the matched address.
map.infoWindow.setTitle("Search Result");
map.infoWindow.setContent(resultName);
map.infoWindow.show(point);
return false; //break out of loop after one candidate with score greater than 80 is found.
}
}
else {
var polygonGeom = new Polygon(candidate.location.spatialReference);
polygonGeom.addRing(candidate.location.rings[0]);
geom = polygonGeom.getCentroid();
point = geom;
console.log(candidate.score);
if (candidate.score > 80) {
console.log(candidate.location);
var attributes = {
address: candidate.address,
score: candidate.score,
locatorName: candidate.attributes.Loc_name
};
point = geom;
var graphic = new Graphic(point, symbol);
//add a graphic to the map at the geocoded location
map.graphics.add(graphic);
//add a text symbol to the map listing the location of the matched address.
map.infoWindow.setTitle("Search Result");
map.infoWindow.setContent(resultName);
map.infoWindow.show(point);
return false; //break out of loop after one candidate with score greater than 80 is found.
}
}
});
if (geom !== undefined) {
map.centerAndZoom(geom, 14);
}
}
}
if (point != undefined || point != null) {
map.centerAndZoom(point, 14);
}
}
});
</script>
<script type="text/javascript">
$(function () {
$("#map").css("height", $(window).height());
$("#map").css("width", $(window).width());
//map_root
$("#map_root").css("height", $(window).height());
$("#map_root").css("height", $(window).width());
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="search">
</div>
<div id="map" style="width: 100%; height: 100%;">
</div>
</form>
</body>
</html>
anyone any suggestion?
Yes i found solution to this problem basically I can append the data which i am receiving using Jquery.
After all it is just an HTML!
But still there can be a better solution please do post it.
$.ajax({
dataType: "json",
type: 'POST',
//url: 'http://11.66.22.44/Geocoder/Query.aspx',
url: 'Query.aspx',
//crossdomain: true,
timeout: 500000,
cache: true,
data: { RequestType: "AutoComplete", AutoCompleteValue: $("#search_input").val() },
success: function (data) {
//$('input.suggest-user').removeClass('ui-autocomplete-loading'); // hide loading image
var actualLength = $(".esriGeocoderResults ul").length;
if (data != null) {
//response(data);
if ($(".esriGeocoderResults ul").length == 0) {
$(".esriGeocoderResults").append('<ul role="presentation">');
}
if ($("#search").hasClass("esriGeocoderResultsOpen") == false) {
$("#search").addClass("esriGeocoderResultsOpen");
}
$(".esriGeocoderResults").css("display", "block");
for (var index = 0; index < data.length; index++) {
if ($(".esriGeocoderResults ul").text().indexOf(data[index]) == -1) {
if (actualLength % 2 == 0) {
$(".esriGeocoderResults ul").append('<li onClick = "locatorClick(this);" class="esriGeocoderResult esriGeocoderResultEven" title="' + data[index] + '" role="menuitem" tabindex="0" data-index="' + (actualLength) + '" data-item="true" data-text="' + data[index] + '">' + data[index] + '</li>');
actualLength++;
}
else {
$(".esriGeocoderResults ul").append('<li onClick = "locatorClick(this);" class="esriGeocoderResult esriGeocoderResultOdd" title="' + data[index] + '" role="menuitem" tabindex="0" data-index="' + (actualLength) + '" data-item="true" data-text="' + data[index] + '">' + data[index] + '</li>');
actualLength++;
}
}
}
$(".esriGeocoderResults ul").bind();
//alert($(".esriGeocoderResults ul").length);
//$(".esriGeocoderResults ul").append('<li><span class="tab">Message Center</span></li>');
}
},
error: function (data) {
alert("error:" + data.statusText);
//$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});

replacing selector 'ul:first-child' with class '.list_wrapper:first-child'

I have a box with text within that scrolling up like the old known marquee tag.
I am using the jquery scrollbox that I found on this website:
http://wmh.github.io/jquery-scrollbox/
now, in my css file I want to replace the ul & il tags with classes, say: .list_wrapper would be instead of ul, and .list would be instead of li, so far so good...
after modifying the css, the scroller stopped to work, i found that i need to modify the "jquery.scrollbox.js" file too, but my knowledge in js is basic.
my page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="/js/jquery.scrollbox.js" type="text/javascript"></script>
<style type="text/css">
#marquee {
height: 180px;
overflow: hidden;
margin: 0;
}
#marquee .list_wrapper {
width: 165px;
line-height: 25px;
list-style-type: none;
padding: 5;
margin: 0;
overflow: hidden;
}
#marquee .list {
overflow: hidden;
}
</style>
<script type="text/javascript">
$(function () {
$('#marquee').scrollbox({
linear: true,
step: 1,
delay: 0,
speed: 65
});
});
</script>
</head>
<body>
<div id="marquee">
<div class="list_wrapper">
<div class="list">• text 1</div>
<div class="list">• text 2</div>
<div class="list">• text 3</div>
<div class="list">• text 4</div>
<div class="list">• text 5</div>
<div class="list">• text 6</div>
</div>
</body>
</html>
heres ths js file (I think there's something to do with the "('ul:first-child') and ('li:first-child'):
/*!
* jQuery Scrollbox
* (c) 2009-2013 Hunter Wu <hunter.wu#gmail.com>
* MIT Licensed.
*
* http://github.com/wmh/jquery-scrollbox
*/
(function($) {
$.fn.scrollbox = function(config) {
//default config
var defConfig = {
linear: false, // Scroll method
startDelay: 2, // Start delay (in seconds)
delay: 3, // Delay after each scroll event (in seconds)
step: 5, // Distance of each single step (in pixels)
speed: 32, // Delay after each single step (in milliseconds)
switchItems: 1, // Items to switch after each scroll event
direction: 'vertical',
distance: 'auto',
autoPlay: true,
onMouseOverPause: true,
paused: false,
queue: null
};
config = $.extend(defConfig, config);
config.scrollOffset = config.direction === 'vertical' ? 'scrollTop' : 'scrollLeft';
if (config.queue) {
config.queue = $('#' + config.queue);
}
return this.each(function() {
var container = $(this),
containerUL,
scrollingId = null,
nextScrollId = null,
paused = false,
backward,
forward,
resetClock,
scrollForward,
scrollBackward;
if (config.onMouseOverPause) {
container.bind('mouseover', function() { paused = true; });
container.bind('mouseout', function() { paused = false; });
}
containerUL = container.children('ul:first-child');
scrollForward = function() {
if (paused) {
return;
}
var curLi,
i,
newScrollOffset,
scrollDistance,
theStep;
curLi = containerUL.children('li:first-child');
scrollDistance = config.distance !== 'auto' ? config.distance :
config.direction === 'vertical' ? curLi.height() : curLi.width();
// offset
if (!config.linear) {
theStep = Math.max(3, parseInt((scrollDistance - container[0][config.scrollOffset]) * 0.3, 10));
newScrollOffset = Math.min(container[0][config.scrollOffset] + theStep, scrollDistance);
} else {
newScrollOffset = Math.min(container[0][config.scrollOffset] + config.step, scrollDistance);
}
container[0][config.scrollOffset] = newScrollOffset;
if (newScrollOffset >= scrollDistance) {
for (i = 0; i < config.switchItems; i++) {
if (config.queue && config.queue.hasChildNodes() && config.queue.getElementsByTagName('li').length > 0) {
containerUL.append(config.queue.getElementsByTagName('li')[0]);
containerUL.remove(containerUL.children('li:first-child'));
} else {
containerUL.append(containerUL.children('li:first-child'));
}
}
container[0][config.scrollOffset] = 0;
clearInterval(scrollingId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
}
};
// Backward
// 1. If forwarding, then reverse
// 2. If stoping, then backward once
scrollBackward = function() {
if (paused) {
return;
}
var curLi,
i,
liLen,
newScrollOffset,
scrollDistance,
theStep;
// init
if (container[0][config.scrollOffset] === 0) {
liLen = containerUL.children('li').length;
for (i = 0; i < config.switchItems; i++) {
containerUL.children('li:last-child').insertBefore(containerUL.children('li:first-child'));
}
curLi = container.children('li:first-child');
scrollDistance = config.distance !== 'auto' ?
config.distance :
config.direction === 'vertical' ? curLi.height() : curLi.width();
container[0][config.scrollOffset] = scrollDistance;
}
// new offset
if (!config.linear) {
theStep = Math.max(3, parseInt(container[0][config.scrollOffset] * 0.3, 10));
newScrollOffset = Math.max(container[0][config.scrollOffset] - theStep, 0);
} else {
newScrollOffset = Math.max(container[0][config.scrollOffset] - config.step, 0);
}
container[0][config.scrollOffset] = newScrollOffset;
if (newScrollOffset === 0) {
clearInterval(scrollingId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
}
};
forward = function() {
clearInterval(scrollingId);
scrollingId = setInterval(scrollForward, config.speed);
};
backward = function() {
clearInterval(scrollingId);
scrollingId = setInterval(scrollBackward, config.speed);
};
resetClock = function(delay) {
config.delay = delay || config.delay;
clearTimeout(nextScrollId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
};
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.startDelay * 1000);
}
// bind events for container
container.bind('resetClock', function(delay) { resetClock(delay); });
container.bind('forward', function() { clearTimeout(nextScrollId); forward(); });
container.bind('backward', function() { clearTimeout(nextScrollId); backward(); });
container.bind('speedUp', function(speed) {
if (typeof speed === 'undefined') {
speed = Math.max(1, parseInt(config.speed / 2, 10));
}
config.speed = speed;
});
container.bind('speedDown', function(speed) {
if (typeof speed === 'undefined') {
speed = config.speed * 2;
}
config.speed = speed;
});
});
};
}(jQuery));
thank you!
open jquery-scrollbox.js and try to change by the hand (not automatically) all ul&li tag on div tag

TypeError using QueryLoader plugin

For page loader i have used the plugin. Following is js:
var QueryLoader = {
overlay: "",
loadBar: "",
preloader: "",
items: new Array(),
doneStatus: 0,
doneNow: 0,
selectorPreload: "body",
ieLoadFixTime: 2000,
ieTimeout: "",
init: function() {
if (navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/) == "MSIE 6.0,6.0") {
//break if IE6
return false;
}
if (QueryLoader.selectorPreload == "body") {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
} else {
$(document).ready(function() {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
});
}
//help IE drown if it is trying to die :)
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
},
ieLoadFix: function() {
var ie = navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/);
if (ie[0].match("MSIE")) {
while ((100 / QueryLoader.doneStatus) * QueryLoader.doneNow < 100) {
QueryLoader.imgCallback();
}
}
},
imgCallback: function() {
QueryLoader.doneNow ++;
QueryLoader.animateLoader();
},
getImages: function(selector) {
var everything = $(selector).find("*:not(script)").each(function() {
var url = "";
if ($(this).css("background-image") != "none") {
var url = $(this).css("background-image");
} else if (typeof($(this).attr("src")) != "undefined" && $(this).attr("tagName").toLowerCase() == "img") {
var url = $(this).attr("src");
}
url = url.replace("url(\"", "");
url = url.replace("url(", "");
url = url.replace("\")", "");
url = url.replace(")", "");
if (url.length > 0) {
QueryLoader.items.push(url);
}
});
},
createPreloading: function() {
QueryLoader.preloader = $("<div></div>").appendTo(QueryLoader.selectorPreload);
$(QueryLoader.preloader).css({
height: "0px",
width: "0px",
overflow: "hidden"
});
var length = QueryLoader.items.length;
QueryLoader.doneStatus = length;
for (var i = 0; i < length; i++) {
var imgLoad = $("<img></img>");
$(imgLoad).attr("src", QueryLoader.items[i]);
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function() {
QueryLoader.imgCallback();
});
$(imgLoad).appendTo($(QueryLoader.preloader));
}
},
spawnLoader: function() {
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
var width = $(window).width();
var position = "fixed";
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
var width = $(QueryLoader.selectorPreload).outerWidth();
var position = "absolute";
}
var left = $(QueryLoader.selectorPreload).offset()['left'];
var top = $(QueryLoader.selectorPreload).offset()['top'];
QueryLoader.overlay = $("<div></div>").appendTo($(QueryLoader.selectorPreload));
$(QueryLoader.overlay).addClass("QOverlay");
$(QueryLoader.overlay).css({
position: position,
top: top,
left: left,
width: width + "px",
height: height + "px"
});
QueryLoader.loadBar = $("<div></div>").appendTo($(QueryLoader.overlay));
$(QueryLoader.loadBar).addClass("QLoader");
$(QueryLoader.loadBar).css({
position: "relative",
top: "50%",
width: "0%"
});
},
animateLoader: function() {
var perc = (100 / QueryLoader.doneStatus) * QueryLoader.doneNow;
if (perc > 99) {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() {
QueryLoader.doneLoad();
});
} else {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() { });
}
},
doneLoad: function() {
//prevent IE from calling the fix
clearTimeout(QueryLoader.ieTimeout);
//determine the height of the preloader for the effect
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
}
//The end animation, adjust to your likings
$(QueryLoader.loadBar).animate({
height: height + "px",
top: 0
}, 500, "linear", function() {
$(QueryLoader.overlay).fadeOut(800);
$(QueryLoader.preloader).remove();
});
}
}
In my html file, I used following Javascript:
<script type='text/javascript'>
QueryLoader.init();
</script>
And css is as following:
.QOverlay {
background-color: #000000;
z-index: 9999;
}
.QLoader {
background-color: #CCCCCC;
height: 1px;
}
I used this for simple example it works well.
But when I used this for my site it is giving error in js file as following:
TypeError: $(...).offset(...) is undefined
var left = $(QueryLoader.selectorPreload).offset()['left'];
So please can you help out from this issue:
Thanks in advance..
Your plugin is not really one. Go see the documentation to see more details.
Anyway, even if it's not a plugin, it could work as an object using some jQuery functions.
First, you shouldn't call the object inside the object function.
IE :
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
Here, you got your first error which you could have seen in the console. It should be :
this.ieTimeout = setTimeout(this.ieLoadFix, this.ieLoadFixTime);
You can start debugging like this, up to your initial error here.

want to show print preview

I want to show a print preview, so I chose to use this plugin.
I have added it to my code:
<%# Page language="c#" AutoEventWireup="false" Inherits="System.Web.UI.Page" %>
<%# Register TagPrefix="CP" TagName="TitleBar" Src="WebUserControl.ascx" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>MyPage</title>
<link href="css/print-preview.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
<script type="text/javascript" src="jquery.tools.min.js"></script>
<script src="jquery.print-preview.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function () {
/*
* Initialise print preview plugin
*/
// Add link for print preview and intialise
$('#aside').prepend('<a class="print-preview">Print this page</a>');
$('a.print-preview').printPreview();
// Add keybinding (not recommended for production use)
$(document).bind('keydown', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 80 && !$('#print-modal').length) {
$.printPreview.loadPrintPreview();
return false;
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<CP:TitleBar Title="User Control Test" TextColor="green" Padding="10" runat="server" />
<div id="aside"></div>
</form>
</body>
</html>
In UserControl I did this:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("p").text("The DOM is now loaded and can be manipulated.");
});
</script>
<p>Not loaded yet.</p>
<table>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
</table>
Problem is, when I add the script in UserControl, the Print-Preview-Plugin is not working.
When I remove the script from the UserControl the print-preview-plugin works fine.
My question is, why is the plugin not working when I add script to the UserControl? How should I call the Print Preview Plugin file code?
/*!
* jQuery Print Previw Plugin v1.0.1
*
* Copyright 2011, Tim Connell
* Licensed under the GPL Version 2 license
* http://www.gnu.org/licenses/gpl-2.0.html
*
* Date: Wed Jan 25 00:00:00 2012 -000
*/
(function($) {
// Initialization
$.fn.printPreview = function() {
this.each(function() {
$(this).bind('click', function(e) {
e.preventDefault();
if (!$('#print-modal').length) {
$.printPreview.loadPrintPreview();
}
});
});
return this;
};
// Private functions
var mask, size, print_modal, print_controls;
$.printPreview = {
loadPrintPreview: function() {
// Declare DOM objects
print_modal = $('<div id="print-modal"></div>');
print_controls = $('<div id="print-modal-controls">' +
'Print page' +
'Close').hide();
var print_frame = $('<iframe id="print-modal-content" scrolling="no" border="0" frameborder="0" name="print-frame" />');
// Raise print preview window from the dead, zooooooombies
print_modal
.hide()
.append(print_controls)
.append(print_frame)
.appendTo('body');
// The frame lives
for (var i=0; i < window.frames.length; i++) {
if (window.frames[i].name == "print-frame") {
var print_frame_ref = window.frames[i].document;
break;
}
}
print_frame_ref.open();
print_frame_ref.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' +
'<head><title>' + document.title + '</title></head>' +
'<body></body>' +
'</html>');
print_frame_ref.close();
// Grab contents and apply stylesheet
var $iframe_head = $('head link[media*=print], head link[media=all]').clone(),
$iframe_body = $('body > *:not(#print-modal):not(script)').clone();
$iframe_head.each(function() {
$(this).attr('media', 'all');
});
if (!$.browser.msie && !($.browser.version < 7) ) {
$('head', print_frame_ref).append($iframe_head);
$('body', print_frame_ref).append($iframe_body);
}
else {
$('body > *:not(#print-modal):not(script)').clone().each(function() {
$('body', print_frame_ref).append(this.outerHTML);
});
$('head link[media*=print], head link[media=all]').each(function() {
$('head', print_frame_ref).append($(this).clone().attr('media', 'all')[0].outerHTML);
});
}
// Disable all links
$('a', print_frame_ref).bind('click.printPreview', function(e) {
e.preventDefault();
});
// Introduce print styles
$('head').append('<style type="text/css">' +
'#media print {' +
'/* -- Print Preview --*/' +
'#print-modal-mask,' +
'#print-modal {' +
'display: none !important;' +
'}' +
'}' +
'</style>'
);
// Load mask
$.printPreview.loadMask();
// Disable scrolling
$('body').css({overflowY: 'hidden', height: '100%'});
$('img', print_frame_ref).load(function() {
print_frame.height($('body', print_frame.contents())[0].scrollHeight);
});
// Position modal
starting_position = $(window).height() + $(window).scrollTop();
var css = {
top: starting_position,
height: '100%',
overflowY: 'auto',
zIndex: 10000,
display: 'block'
}
print_modal
.css(css)
.animate({ top: $(window).scrollTop()}, 400, 'linear', function() {
print_controls.fadeIn('slow').focus();
});
print_frame.height($('body', print_frame.contents())[0].scrollHeight);
// Bind closure
$('a', print_controls).bind('click', function(e) {
e.preventDefault();
if ($(this).hasClass('print')) { window.print(); }
else { $.printPreview.distroyPrintPreview(); }
});
},
distroyPrintPreview: function() {
print_controls.fadeOut(100);
print_modal.animate({ top: $(window).scrollTop() - $(window).height(), opacity: 1}, 400, 'linear', function(){
print_modal.remove();
$('body').css({overflowY: 'auto', height: 'auto'});
});
mask.fadeOut('slow', function() {
mask.remove();
});
$(document).unbind("keydown.printPreview.mask");
mask.unbind("click.printPreview.mask");
$(window).unbind("resize.printPreview.mask");
},
/* -- Mask Functions --*/
loadMask: function() {
size = $.printPreview.sizeUpMask();
mask = $('<div id="print-modal-mask" />').appendTo($('body'));
mask.css({
position: 'absolute',
top: 0,
left: 0,
width: size[0],
height: size[1],
display: 'none',
opacity: 0,
zIndex: 9999,
backgroundColor: '#000'
});
mask.css({display: 'block'}).fadeTo('400', 0.75);
$(window).bind("resize..printPreview.mask", function() {
$.printPreview.updateMaskSize();
});
mask.bind("click.printPreview.mask", function(e) {
$.printPreview.distroyPrintPreview();
});
$(document).bind("keydown.printPreview.mask", function(e) {
if (e.keyCode == 27) { $.printPreview.distroyPrintPreview(); }
});
},
sizeUpMask: function() {
if ($.browser.msie) {
// if there are no scrollbars then use window.height
var d = $(document).height(), w = $(window).height();
return [
window.innerWidth || // ie7+
document.documentElement.clientWidth || // ie6
document.body.clientWidth, // ie6 quirks mode
d - w < 20 ? w : d
];
} else { return [$(document).width(), $(document).height()]; }
},
updateMaskSize: function() {
var size = $.printPreview.sizeUpMask();
mask.css({width: size[0], height: size[1]});
}
}
})(jQuery);
$('a.print-preview').printPreview() really is not a function, because it doesn't have such.
Try something like:
$('a.print-preview').onClick(printPreview);

Categories

Resources