The slider should function nice and smooth. Instead the animation isn't working smoothly. Here are the HTML, CSS and Javascript. I looked and looked and looked and can't find the clue. Rotating is not smooth, caption does not match the image, the last image doesn't even appear. (Here is the actual demo).
Here are some sample images showing a bit of the problem:
<IMG ID="slideshowPicturePlaceholder" src="/_layouts/images/GEARS_AN.GIF" style="display:none"/>
<div id="slideshowContentArea" style="display:none; width:255px;">
<div class="main_view">
<div class="window">
<div class="image_reel"> </div>
</div>
<div class="paging">
1
2
3
4
</div>
</div>
</div>
<style type="text/css">
/*--Main Container--*/
.main_view {
float: left;
position: relative;
}
/*--Window/Masking Styles--*/
.window {
height: 286px; width: 790px;
overflow: hidden; /*--Hides anything outside of the set width/height--*/
position: relative;
}
.image_reel {
position: absolute;
top: 0; left: 0;
}
.image_reel img {float: left;}
/*--Paging Styles--*/
.paging {
position: absolute;
bottom: 40px; right: -7px;
width: 178px; height:47px;
z-index: 100; /*--Assures the paging stays on the top layer--*/
text-align: center;
line-height: 40px;
background: url(paging_bg2.png) no-repeat;
display: none; /*--Hidden by default, will be later shown with jQuery--*/
}
.paging a {
padding: 5px;
text-decoration: none;
color: #fff;
}
.paging a.active {
font-weight: bold;
background: #920000;
border: 1px solid #610000;
-moz-border-radius: 3px;
-khtml-border-radius: 3px;
-webkit-border-radius: 3px;
}
.paging a:hover {font-weight: bold;}
</style>
<script type="text/javascript" src="_layouts/jquery/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="_layouts/jquery/jquery.cycle.all.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function GetAllImages()
{
$("#slideshowPicturePlaceholder").css("display", "block");
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>";
soapEnv += "<listName>NewsRotator</listName>";
soapEnv += "<query><Query><OrderBy Override='TRUE'><FieldRef Name='Created' Ascending='FALSE' /></OrderBy></Query></query>";
soapEnv += "<viewFields><ViewFields><FieldRef Name='Title'/><FieldRef Name='ows_FileLeafRef'/><FieldRef Name='NewsLink'/><FieldRef Name='Description'/></ViewFields></viewFields><rowLimit></rowLimit>";
soapEnv += "</GetListItems></soapenv:Body></soapenv:Envelope>";
var port = window.location.port;
if (port.length <= 0)
port = "";
else
port = ":" + port;
var webservice = window.location.protocol + "//" + window.location.hostname + port + L_Menu_BaseUrl + "/_vti_bin/lists.asmx";
$.ajax(
{
url : webservice,
type : "POST",
dataType : "xml",
data : soapEnv,
complete : processQueryResults,
contentType : "text/xml; charset=utf-8",
error : function (xhr)
{
alert('Error! Status = ' + xhr.status);
}
});
}
function processQueryResults(xData, status)
{
var port = window.location.port;
if (port.length <= 0)
port = "";
else
port = ":" + port;
// Change the below to point to your image library
var imageURL = window.location.protocol + "//" + window.location.hostname + port + L_Menu_BaseUrl + "/Splash Image Rotator/";
var itemURL = window.location.protocol + "//" + window.location.hostname + port + L_Menu_BaseUrl + "/Splash Image Rotator/Forms/DispForm.aspx?ID=";
// $("#slideshowContentArea").html("")
$(xData.responseXML).find("z\\:row").each(function ()
{
var title = $(this).attr("ows_Title");
var headlines = $(this).attr("ows_Description");
var imageLink = imageURL + $(this).attr("ows_FileLeafRef").substring($(this).attr("ows_FileLeafRef").indexOf('#') + 1);
// // var itemLink = itemURL + $(this).attr("ows_ID");
var itemLink = $(this).attr("ows_NewsLink");
//var liHtml = "<div><a href='" + itemLink + "' target='_blank'><img src='" + imageLink + "'/></a></div>";
//var liHtml ="<a target='_blank' border='0' href='"+itemLink+"'><img src='"+ imageLink +"'/></a>";
var liHtml = "<a href='"+itemLink+"' target='_blank' border='0'><img src='" + imageLink +"'/></a><p>"+ title + " - " + headlines + "</p>";
$(".image_reel").append(liHtml);
});
$("#slideshowPicturePlaceholder").css("display", "none");
$("#slideshowContentArea").css("display", "block");
// Show the paging and activate its first link
$(".paging").show();
$(".paging a:first").addClass("active");
// Get size of the image, how many images there are, then determin the size of the image reel.
var imageWidth = $(".window").width();
var imageSum = $(".image_reel img").size();
var imageReelWidth = imageWidth * imageSum;
// Adjust the image reel to its new size
$(".image_reel").css(
{
'width' : imageReelWidth
}
);
// Paging and Slider Function
rotate = function ()
{
var triggerID = $active.attr("rel") - 1;
// Get number of times to slide
var image_reelPosition = triggerID * imageWidth;
// Determines the distance the image reel needs to slide
$(".paging a").removeClass('active');
// Remove all active class
$active.addClass('active');
// Add active class (the $active is declared in the rotateSwitch function)
// Slider Animation
$(".image_reel").animate(
{
left : - image_reelPosition
}
, 500);
}
;
// Rotation and Timing Event
rotateSwitch = function ()
{
play = setInterval(function ()
{
// Set timer - this will repeat itself every 7 seconds
$active = $('.paging a.active').next();
// Move to the next paging
if ($active.length === 0)
{
// If paging reaches the end...
$active = $('.paging a:first');
// go back to first
}
rotate();
// Trigger the paging and slider function
}
, 3000);
// Timer speed in milliseconds (7 seconds)
}
;
rotateSwitch();
// Run function on launch
// On Hover
$(".image_reel a").hover(function ()
{
clearInterval(play);
// Stop the rotation
}
, function ()
{
rotateSwitch();
// Resume rotation timer
} );
// On Click
$(".paging a").click(function ()
{
$active = $(this);
// Activate the clicked paging
// Reset Timer
clearInterval(play);
// Stop the rotation
rotate();
// Trigger rotation immediately
rotateSwitch();
// Resume rotation timer
return false;
// Prevent browser jump to link anchor
}
);
}
GetAllImages();
});
</script>
This issue might cause because of using position property in CSS.
position absolute is not necessary for '.image_reel' class, try with float:left.
Is this question still active? try to remove absolute position from your "image_reel" class
Related
Hi can anyone have a look at the below and tell me why its not working?
I am trying to get it all to create a popup box with a countdown timer and set a cookie so it doesn't do the popup box on every page. It's supposed to set a cookie and detect it and I think it's doing that but now the count down timer isn't visibly counting down.
$(document).ready(function() {
if(readCookie('oldsite') != 'stay') //Unless we find the cookie, we show the banner ...
{
var time_left = 12;
var cinterval;
cinterval = setInterval('time_dec()', 1000);
var id = '#dialog';
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(500);
$('#mask').fadeTo("slow",0.9);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
//if Disagree word is clicked
$('#disagree').click(function () {
$(this).hide();
$('.window').hide();
$('#mask').hide();
time_left = 0;
});
//if mask is clicked
$('#mask').click(function () {
createCookie('oldsite', 'stay', 1); //create the cookie for 1 day
$(this).hide();
$('.window').hide();
});
}
//Functions
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 1){
var originalstring = document.getElementById('countdown2').innerHTML;
var newstring = originalstring.replace('seconds','second');
document.getElementById('countdown2').innerHTML = newstring;
window.location.replace("http://cadfemukandireland.com/");
clearInterval(cinterval);
}
}
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
});
The css is:
/* CSS Document */
#mask {
position: absolute;
left: 0;
top: 0;
z-index: 9000;
background-color: #000;
display: none;
}
#boxes .window {
position: absolute;
left: 0;
top: 0;
width: 440px;
height: 200px;
display: none;
z-index: 9999;
padding: 20px;
border-radius: 15px;
text-align: center;
}
#boxes #dialog {
width: 750px;
height: 300px;
padding: 75px 50px 10px 50px;
background-color: #ffffff;
font-family: 'Segoe UI Light', sans-serif;
font-size: 15pt;
}
#popupfoot {
font-size: 16pt;
position: absolute;
bottom: 0px;
width: 350px;
left: 225px;
padding-bottom:20px;
}
#disagree {
cursor:pointer;
}
and the html is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxes">
<div id="dialog" class="window">
<p>As part of our re branding to CADFEM, we have a new website</p>
<p>You will be redirected to the new website <span id="countdown2">in <span id="countdown">12</span> seconds</span>.</p>
<div id="popupfoot" style="padding-bottom:100px;"> If you wish to stay on the old website, please click <a id="disagree"><b><u>here</u></b></a>
</div>
</div>
<div id="mask"></div>
You can use Creative Tools
<div id="timer"></div>
<script>
$(document).ready(function(){
$("#timer").countdown({
duration : 30, // Discount start from defined number (in this case 30 seconds) DEFAULT: 0
interval : 1000, // interval in millisecond (DEFAULT: interval every 1000ms (1 second))
text_before : "Redirection begins in exactly ", // initial text before number (example: Redirection begins in exactly 30), DEFAULT: blank
text_after : "seconds" // initial text after number (example: 30seconds), DEFAULT: blank
},
// callback function when discount stop on 0
function(){
this.html("Done counting, redirecting.");
window.location = "http://www.google.com";
});
});
</script>
Also cookie function:
// Set a session cookie
$.cookie('the_cookie', 'the_value');
$.cookie('the_cookie'); // -> 'the_value'
// Set a cookie that expires in 7 days
$.cookie('the_cookie', 'the_value', { expires: 7 });
// delete the cookie
$.cookie('the_cookie', null);
You can copy this 2 functions and integrate with your code or use whole creative tools.
Also you can use Local Storage function what if storage is disabled or not exist use cookie:
// Set a session storage
$.storage('the_name', 'the_value');
// Get session storage
$.storage('the_name');
// delete storage
$.storage('the_name', null);
You counter is not working because you are parsing your time_dec function as a string
cinterval = setInterval('time_dec()', 1000);
remove the comma's and the () and you should be fine
cinterval = setInterval(time_dec, 1000);
See working jsfiddle here https://jsfiddle.net/domjgreen/zngLk99q/
The following code creates the effect when one image goes to white and then white is changed with another image (demo):
HTML:
<body>
<div class="page-bg" id="page-background1"></div>
<!-- <div class="page-bg" id="page-background2"></div> -->
</body>
JavaScript:
url = "http://example.com/picture.png";
$("#page-background1")
.animate({
opacity: 0
}, 'slow', function () {
$("#page-background1")
.css({
'background-image': 'url(' + url + ')'
})
.animate({
opacity: 1
});
});
But I would like to change one image directly with another (without white color in between), but with fadeOut/fadeIn effect. How should I do it? Looks like usage of the second div should help, but I can not find working solution.
Updated, I tried to apply Stacking elements with Z-index to get the desired effect. I also created a kind of "stack" of images where z-index is changed for the image that was hidden; the most recently hidden element is changed for a smaller z-index value in comparison to other images in the "stack". The code supports multiple images in the photos array, because it creates an individual div for each image.
var photos = [{
url: 'https://drscdn.500px.org/photo/97037403/m=900/d924fc03d69a82a604129011300916be'
}, {
url: 'https://drscdn.500px.org/photo/97037259/m=900/030e1598b7822cd6c41beb4c7a4e466d'
}, {
url: 'https://drscdn.500px.org/photo/97158643/m=900/4ae40d67ef546341111a32f5176694c8'
}];
//z-index, start value -1
//z-index can be either positive or negative value
//based on this answer http://stackoverflow.com/a/491105/2048391
var zIndex = -1;
//first foto in the array shown/hidden first
var visibleIndex = 0;
//initialize
//by creating div for each image/url
for (i = 0; i < photos.length; i++) {
var div = document.createElement("div");
div.id = "page-background" + (i + 1);
div.setAttribute("class", "page-bg");
div.style.zIndex = zIndex;
var url = "url('" + photos[i].url + "')";
div.style.background = "#505D6E " + url + " no-repeat center center fixed";
document.body.appendChild(div);
zIndex = zIndex - 1;
//and add div id to the photos array
photos[i].id = "page-background" + (i + 1);
}
function changeBackground() {
var hideItemIndex = visibleIndex % photos.length;
var showItemIndex = (visibleIndex + 1) % photos.length;
var hideItemId = "#" + photos[hideItemIndex].id;
var showItemId = "#" + photos[showItemIndex].id;
//hide current image with animation
//after which show the next image with animation
$(hideItemId).animate({
opacity: 0
}, "slow", function() {
$(showItemId)
.animate({
opacity: 1
}, "slow");
//change z-index for the item that was hidden
//by moving it to the bottom of the stack
$(hideItemId).css("z-index", zIndex);
$(hideItemId).css("opacity", 1);
});
zIndex = zIndex - 1;
visibleIndex = visibleIndex + 1;
}
//make sure that there's at least 2 images in the array
if (photos.length > 1) {
setInterval(function() {
changeBackground();
}, 2000);
}
.page-bg {
border: 1px solid black;
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Alternative way of doing the same thing as above. Below only visible and the next div element exist, and the hidden div is removed for performance reasons, like suggested by LA_
var photos = [{
url: 'https://drscdn.500px.org/photo/97037403/m=900/d924fc03d69a82a604129011300916be'
}, {
url: 'https://drscdn.500px.org/photo/97037259/m=900/030e1598b7822cd6c41beb4c7a4e466d'
}, {
url: 'https://drscdn.500px.org/photo/97158643/m=900/4ae40d67ef546341111a32f5176694c8'
}];
//z-index, start value 100000
//z-index could be a larger number
//based on this answer http://stackoverflow.com/a/491105/2048391
var zIndex = -1;
//first foto in the array shown/hidden first
var visibleIndex = 0;
//initialize
//by creating div for each image/url
for (i = 0; i < photos.length; i++) {
//only two images are created
if (i < 2)
createDiv(i, (i + 1) );
//and add div id to the photos array
photos[i].id = "page-background" + (i + 1);
}
function changeBackground() {
var hideItemIndex = visibleIndex % photos.length;
var showItemIndex = (visibleIndex + 1) % photos.length;
var hideItemId = "#" + photos[hideItemIndex].id;
var showItemId = "#" + photos[showItemIndex].id;
//hide current image with animation
//after which show the next image with animation
$(hideItemId).animate({
opacity: 0
}, "slow", function () {
$(showItemId)
.animate({
opacity: 1
}, "slow");
//remove the item that was hidden
$(hideItemId).remove();
});
var nextItemIndex = (visibleIndex + 2) % photos.length;
//create the next div with picture
createDiv(nextItemIndex, (nextItemIndex + 1) );
visibleIndex = visibleIndex + 1;
}
//make sure that there is at least 2 photos
if (photos.length > 1) {
setInterval(function () {
changeBackground();
}, 2000);
}
function createDiv(index, divIdNro) {
var div = document.createElement("div");
div.id = "page-background" + divIdNro;
div.setAttribute("class", "page-bg");
div.style.zIndex = zIndex;
var url = "url('" + photos[index].url + "')";
//div.style.backgroundImage = url;
div.style.background = "#505D6E " + url + " no-repeat center center fixed";
document.body.appendChild(div);
zIndex = zIndex - 1;
}
.page-bg {
border:1px solid black;
height:100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
here's a fiddle as snippets not working sat the mo, you can put the speed of the fade in milliseconds or keyword, it's at slow. I've left it on button click and not passed in the url but take out my button click function and put the code into your setinterval func, also set the url in jquery back to url variable
$('button').on('click',function(){
$("#page-background1").fadeOut( "slow", function() {
$("#page-background1")
.css({
'background-image': 'url(http://lorempixel.com/400/400/sports/2)'
});});
$("#page-background1").fadeIn('slow');
});
.page-bg{
min-width:500px;
min-height:500px;
}
#page-background1{
background-image: url(http://lorempixel.com/400/400/sports/1);
background-size:400px 400px;
background-repeat: no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me to change the background</button>
<div class="page-bg" id="page-background1">;</div>
Change the javascript to:
url = "http://example.com/picture.png";
.animate({
opacity: 0.5
}, 'fast', function () {
$("#page-background1")
.css({
'background-image': 'url(' + url + ')'
})
.animate({
opacity: 1
});
});
I'm working on Some JS project And I'm trying to change scrolling speed and scroll to next division height of 100% ...
My idea for scrolling Down >
Detect InnerHTML height + detect scroll space from top , detect position using innerHTML height and a counter ....
when user scrolles down for fisrt time , position is 0 and scrollTop is more, so function is called and brings user to next div . (its OK)
but then ,what can I do to bring user back to previous div when user scrolls UP ?
Here are my codes :
<html>
<head>
<style>
body,html {
margin: 0;
height: 100%;
width: 100%;
}
.scrollers {
height: 100%;
width: 100%;
transition: all 1s;
-webkit-transition: all 1s;
}
#N1 {
background-color: #725a5a;
}
#N2 {
background-color: #4a478d;
}
#N3 {
background-color: #478d6f;
}
#N4 {
background-color: #8d8a47;
}
#status {
text-align: center;
width: 100%;
color: #000;
font-size: 20px;
position: fixed;
z-index: 10;
top: 5px;
}
</style>
<script>
var $firstPosition = 1;
window.onscroll = scroll;
var $counter = 0;
var $status = "play";
function scroll() {
var $sctop = document.body.scrollTop;
var $inrH = window.innerHeight;
var $secst;
if (($status=="pause") || ($secst=="pause")){
} else if ($status=="play"){
var $position = $counter * $inrH;
if ($sctop>$position) {
$counter++;
$position = $counter * $inrH;
$status = "pause";
$secst = "pause";
callMeInterval = setInterval( function() { if(!($sctop==$position)){window.scrollTo(0,$firstPosition);$firstPosition++;$sctop = document.body.scrollTop;document.getElementById("status").innerHTML = "sctop = " + $sctop + " $position = " + $position + "$counter = " + $counter; } else if($sctop==$position) {$status = "play";secst==""} }, 1 );
}
// Problem Starts Here
else {
$counter--;
$position = $counter * $inrH;
$status = "pause";
$secst = "pause";
callMeInterval = setInterval( function() { if(!($sctop==$position)) {$firstPosition--;window.scrollTo(0,$firstPosition);$sctop = document.body.scrollTop;document.getElementById("status").innerHTML = "sctop = " + $sctop + " $position = " + $position + "$counter = " + $counter; } else if($sctop==$position) {secst=="";$status = "play"} }, 1 );
}
}
}
</script>
</head>
<body>
<div id="status">
</div>
<div id="N1" class="scrollers">
</div>
<div id="N2" class="scrollers">
</div>
<div id="N3" class="scrollers">
</div>
<div id="N4" class="scrollers">
</div>
</body>
</html>
I'm sure the whole thing is just easier with JQUERY , but this is my project for Javascript Class . Thanks
You don't clear your interval, so this is the reason of flickering.
clearInterval(callMeInterval);
I recommend you to use requestAnimationFrame instead of using window.setInterval
Here you have working sample rebuild with requestAnimationFrame
var lastScrollPosition = document.body.scrollTop,
sectionNo = 0;
function doScroll(scrollPosition, step, first) {
var height = window.innerHeight,
min = height * sectionNo,
max = height * (sectionNo + 1);
scrollPosition += step;
if (min < scrollPosition && scrollPosition < max) {
// here should be some animation control
document.body.scrollTop = scrollPosition;
// Call next animation frame
window.requestAnimationFrame(doScroll.bind(null, scrollPosition, step));
} else {
// It fires, when scroll is done
lastScrollPosition = scrollPosition;
document.addEventListener("scroll", scrollListener);
}
}
function scrollListener(e) {
var scrollPosition = document.body.scrollTop,
step;
// Stop scroll listening
document.removeEventListener("scroll", scrollListener);
// Get direction
step = scrollPosition >= lastScrollPosition ? 5 : -5;
// Go back to initial position
document.body.scrollTop = lastScrollPosition;
// Animate
window.requestAnimationFrame(doScroll.bind(null, lastScrollPosition, step, true));
}
document.addEventListener("scroll", scrollListener);
I have made this minimal test jsfiddle to show images and navigate with thumbnails, next and previous and also run as a slideshow.
It seems to be working OK, except that I can not get the current displayed image to fadeOut prior to the fadeIn of the next image.
Initially all the images were placed in a stack in the #holder DIV and then FadeIn and FadeOut worked as I expected, but I need to have the images in an array and load as required, because there will be several different values, associated with each image.
I probably have made some fundamental mistake or I do not understand how FadeIn and FadeOut properly work, as I am not an expert in javascript and jquery and I just get by, by looking at examples on here and similar sites.
I suspect I may need to somehow force a delay before loading the next image, but I can not work out how to do that.
Thanks
<style type='text/css'>
#holder { position: absolute; top: 100px; background-color:#CCCCCC;
width: 300px; height: 200px;
}
.slides { position: relative; top: 0px;
display: none;
}
#thumbs li
{
display: inline;
list-style-type: none;
padding-right: 6px;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
// define Global Vars
var timerON = null;
var files = [
["http://dummyimage.com/300x200/000/fff&text=Array-01", "http://dummyimage.com/40x40/000/fff&text=01","Title-01"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-02", "http://dummyimage.com/40x40/000/fff&text=02","Title-02"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-03", "http://dummyimage.com/40x40/000/fff&text=03","Title-03"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-04", "http://dummyimage.com/40x40/000/fff&text=04","Title-04"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-05", "http://dummyimage.com/40x40/000/fff&text=05","Title-05"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-06", "http://dummyimage.com/40x40/000/fff&text=06","Title-06"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-07", "http://dummyimage.com/40x40/000/fff&text=07","Title-07"]
]
var numImages = files.length;
// initial routines
showImage(1);
buildThumbs();
function showImage(num) {
//$('#holder img').fadeOut();
if ( $('#holder img').length > 0 ) { // fadeout existing
$("#holder img").fadeOut(700);
//alert("Faded OUT");
}
$("#holder").html('<img id="' + num + '" src="' + files[num-1][0] + '" style="display:none;"' + '" />');
$("#holder img").fadeIn(700);
//alert("Faded IN");
}
function buildThumbs() {
var thumbs = "";
for (cnt=0; cnt<files.length; cnt++) {
thumbs += '<li><a href="#" id="' + (cnt + 1) + '"><img src="' + files[cnt][1] + '" /></li>';
}
$('#thumbs').html(thumbs);
}
// Initialise routines for acting on click events
$(document).ready(function() {
$('#prev').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == 1) {
// at first position
}
else {
showImage(currImage-1); }
});
$('#next').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
// at last position
}
else {
showImage(currImage+1);
}
});
$('#thumbs a').click( function () {
var selImage = parseInt($(this).attr('id'));
var currImage = parseInt($('#holder img:visible').attr("id"));
showImage(selImage);
});
$('#slideShowBtn').click( function () {
slideShowCheck();
});
});
function slideShowCheck() {
if(timerON != null) {
clearTimeout(timerON);
timerON = null;
$('#slideShowBtn').text('Play Slideshow');
} else {
$('#slideShowBtn').text('Stop Slideshow');
slideShow();
}
}
function slideShow() {
var nextImage = 0;
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
nextImage = 1;
} else {
nextImage = currImage + 1;
}
showImage(nextImage);
timerON = setTimeout(slideShow, 3000);
}
});//]]>
</script>
</head>
<body>
<p>
<button id="prev">« Prev</button>
<button id="next">Next »</button>
</p>
<ul id="thumbs">
</ul>
<p>
<button id="slideShowBtn">Play Slideshow</button>
</p>
<div id="holder">
</div>
<div style="clear:both;"></div>
<ul id="thumbs2">
</ul>
</body>
</html>
Callbacks, callbacks, callbacks.
JS does alot of things async, so you will need to make use of a callback on that fadein.
$(ITEM1).fadeOut("fast", function() {
alert("all the way faded out");
$(ITEM2).fadeIn("fast");
});
Here's your fixed fiddle.
I hope that someone will know how to help me with this problem, I am new to javaScript and XML. Basically I have the xml file with list of products, I have managed to dynamically load the data into an ul li list in my html page, the li elements has title and image, and now I need to be able to click on this li element and load remaining data for a specific product into a new page (or div). I am getting the "Uncaught ReferenceError: i is not defined" My question is how could I load the correct remaining data after clicking on a specific product from the list of products. (I hope that my explanation is clear enough) here is my code, the first function produces the ul li list in the html page, the displayPRInfo() function should load the data into showPrInfo div for any product which was clicked.
please help me, any help appreciated , thanks for reading.
function loadProducts() {
var liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>");
var divOpen=("</p><div class='prod-sq-img'>");
var closingTags=("</div></li>");
var txt;
var image;
var title;
var x=xmlDoc.getElementsByTagName("product");
for (i=0;i<x.length;i++)
{
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
image=(x[i].getElementsByTagName("imgfile")[0].childNodes[0].nodeValue);
txt= liOpen + title + divOpen + image + closingTags ;
document.getElementById("ulList").innerHTML+=txt;
}
}
function displayPRInfo(i)
{
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
euPriceRet=(x[i].getElementsByTagName("euror")[0].childNodes[0].nodeValue);
euPriceTrade=(x[i].getElementsByTagName("eurot")[0].childNodes[0].nodeValue);
euPriceSet=(x[i].getElementsByTagName("eset")[0].childNodes[0].nodeValue);
minimumQuantity=(x[i].getElementsByTagName("mqty")[0].childNodes[0].nodeValue);
description=(x[i].getElementsByTagName("desc")[0].childNodes[0].nodeValue);
prBigImg=(x[i].getElementsByTagName("pimgfile")[0].childNodes[0].nodeValue);
prInfo=title+"<br>"+euPriceRet+"<br>"+euPriceTrade+"<br> "+euPriceSet+"<br> "+minimumQuantity+"<br>"+description+"<br>"+ prBigImg ;
document.getElementById("showPrInfo").innerHTML=prInfo;
}
You can use jQuery to manipulate xml and set onclick events.
function loadProducts() {
var products = $(xmlDoc).find('product');
for (var i = 0; i < products.length; i++) {
$('#ulList').append('<li id="product_' + i + '"><p>' + $(products[i]).find('title').text() + '</p><div class="prod-sq-img">' + $(products[i]).find('imgfile').text() + '</div></li>');
$('#product_' + i).click(displayPRInfo.bind($('#product_' + i), products[i]));
}
}
function displayPRInfo(xmlProduct) {
var title= $(xmlProduct).find('title).text();
var euPriceRet = $(xmlProduct).find('euror').text();
var euPriceTrade = $(xmlProduct).find('eurot').text();
var euPriceSet = $(xmlProduct).find('eset').text();
var minimumQuantity = $(xmlProduct).find('mqty').text();
var description = $(xmlProduct).find('desc').text();
var prBigImg = $(xmlProduct).find('pimgfile').text();
var prInfo = title+"<br>"+euPriceRet+"<br>"+euPriceTrade+"<br> "+euPriceSet+"<br> "+minimumQuantity+"<br>"+description+"<br>"+ prBigImg ;
$('#showPrInfo').html(prInfo);
}
I haven't tried the whole script but for sure you have to move this:
liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>")
into the for loop
for (i=0; i<x.length; i++) {
title=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
image=(x[i].getElementsByTagName("imgfile")[0].childNodes[0].nodeValue);
liOpen=("<li onclick='displayPRInfo(" + i + ")'><p>");
txt= liOpen + title + divOpen + image + closingTags ;
document.getElementById("ulList").innerHTML+=txt;
}
where acctually i is defined
I found this and it helped me a bit, the thing is that I want to load images by request, not loading them all at once but by clicking a button and set the img src with the xml data, I have this...
<!doctype html>
<html lang="es">
<head>
<style>
#iosslider_nav {
height: 13px;
right: 10px;
/* align right side */
/*left: 10px;*/
/* align left side */
bottom: 10px;
/*position: absolute;*/
/* set if needed */
/*margin-top: 10px;*/
/* remove if position is absolute */
}
#iosslider_nav .btn {
width: 13px;
height: 13px;
background: #eaeaea;
margin: 0 5px 0 0;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
border-radius: 100%;
cursor: pointer;
float: left;
/* ie 7/8 fix */
background: url('../images/bull_off.png') no-repeat\9;
}
</style>
</head>
<body>
<div id="ninja_slider"></div>
<div id="iosslider_nav"></div>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var xmlDoc = loadXMLDoc("xml/xml_data.xml");
// generic load xml data function
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // code for IE5 and IE6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", filename, false);
xhttp.send();
return xhttp.responseXML;
}
set_slider();
//set_navigation('xml/xml_data.xml', 'iosslider_nav');
function set_slider() {
var item_div = $(xmlDoc).find('desk');
var item_btn = $(xmlDoc).find('desk');
var item_img = $(xmlDoc).find('desk');
// Object.bind() handler for ie 7/8
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
// create main div's
for (var i = 0; i < item_div.length; i++) {
$('#ninja_slider').append('<div id="item_div' + i + '"><img id="item_img' + i + '" src="" class="ninja_item"></div>');
$('#item_div' + i).on('click', load_current.bind($('#item_div' + i), item_div[i]));
}
// load first element
$('#ninja_slider #item_div0 .item_anchor img').attr('src', $(item_img[0]).find('image').text());
// create nav div's
for (var i = 0; i < item_btn.length; i++) {
$('#iosslider_nav').append('<div id="item_btn' + i + '" class="btn"></div>');
$('#item_btn' + i).on('click', load_current.bind($('#item_btn' + i), item_btn[i]));
}
}
function load_current(xmlData) {
var image = $(xmlData).find('image').text();
var src = image;
//console.log(image);
var item_img = $(xmlDoc).find('desk');
for (var i = 0; i < item_img.length; i++) {
$('#ninja_slider').append('<div id="item_div' + i + '"><img id="item_img' + i + '" src="' + $(item_img[i]).find('image').text() + '" class="ninja_item"></div>');
}
}
function set_navigation(url, id) {
$.ajax({
url: url,
async: false,
type: "GET",
data: "xml",
success: function (xml) {
$(xml).find("desk").each(function () {
var item_nav = document.getElementById(id),
click_item = document.createElement("div");
item_nav.appendChild(click_item);
click_item.className = click_item.className + "btn";
});
}
});
}
</script>
</body>
</html>
hope it makes sense...