Solved

Javascript image fader with links and random

Posted on 2014-01-24
8
265 Views
Last Modified: 2014-06-01
I am trying to setup a random image fader that has links.  I had the code for random image fader and was trying to add links.  I have the links and everything rendering properly, but when I try to click on one of the images, the link where I am ending up does not match the image I clicked.

Here is the full code.  
<html>
<head>

<style>
.showhand
{
    cursor:pointer;
}
</style>
<script type="text/javascript">
    var nindex = 0;
    function tFader(a_items, a_lnks, a_tpl) {

        // validate parameters and set defaults
        if (!a_items) return alert("items structure is missing");
        if (typeof (a_items) != 'object') return alert("format of the items structure is incorrect");
        if (a_items[a_items.length - 1] == null) return alert("last element of the items structure is undefined");

        if (!a_lnks) return alert("links structure is missing");
        if (typeof (a_lnks) != 'object') return alert("format of the items structure is incorrect");
        if (a_lnks[a_lnks.length - 1] == null) return alert("last element of the links structure is undefined");
        
        if (!a_tpl) a_tpl = [];
        for (var i = 0; i < A_TSLIDEDEFS.length; i += 2)
            if (a_tpl[A_TSLIDEDEFS[i]] == null)
                a_tpl[A_TSLIDEDEFS[i]] = A_TSLIDEDEFS[i + 1];

        // save config parameters in the slider object
        this.a_tpl = a_tpl;
        this.a_lnks = a_lnks;
        this.a_items = a_tpl.random ? tslide_randomize(a_items, a_lnks) : a_items;
        var items = [];
        var a_linkstest = [];
        var string1 = "";

        for (i = 0; i < this.a_items.length; i++) {
            items[i] = this.a_items[i].split("|")[0];
            a_linkstest[i] = this.a_items[i].split("|")[1];
        }

        this.a_lnks = a_linkstest;
        this.a_items = items;

        // initialize parameters, assign methods	
        this.n_currentSlide = 0;
        this.f_goto = tslide_goto;
        this.f_run = function () { this.b_running = 1; this.f_goto(); };
        this.f_stop = function () { this.b_running = 0; clearTimeout(this.o_timerS); };
        this.f_fadeIn = tslide_fadeIn;
        this.f_fadeOut = tslide_fadeOut;
        this.f_slideOp = tslide_slideOp;

        // register in the global collection	
        if (!window.A_SLIDES)
            window.A_SLIDES = [];
        this.n_id = window.A_SLIDES.length;
        window.A_SLIDES[this.n_id] = this;

        // generate control's HTML
        var s_attributes = ' '
		+ (a_tpl['css'] ? ' class="' + a_tpl['css'] + '"' : '')
		+ (a_tpl['width'] ? ' width="' + a_tpl['width'] + '"' : '')
		+ (a_tpl['height'] ? ' height="' + a_tpl['height'] + '"' : '')
		+ (a_tpl['alt'] ? ' title="' + a_tpl['alt'] + '" alt="' + a_tpl['alt'] + '"' : '');

        this.a_imgRefs = [];
        if (this.a_lnks[0].length != 0) {
            document.write('<img class="rotatorclass" src="' + this.a_items[0] + '"' + s_attributes + ' onclick="window.location.href =\'' + this.a_lnks[0] + '\';"' + ' id="tslide' + this.n_id + '_0" />');
        }
        else {
            
            document.write('<img class="rotatorclass" src="' + this.a_items[0] + '"' + s_attributes + ' name="tslide' + this.n_id + '_0" />');
            // document.write ('<img class="rotatorclass" src="', this.a_items[0] , '"', s_attributes, ' name="tslide', this.n_id, '_0" />');
        }
        this.a_imgRefs[0] = document.images['tslide' + this.n_id + '_0'];
        this.n_currentSlide = 0;

        // exit on old browsers
        if (!this.a_imgRefs[0] || !this.a_imgRefs[0].style || this.a_imgRefs[0].style.marginLeft == null)
            return;

        for (var i = 1; i < this.a_items.length; i++) {
            if (this.a_lnks.length > 1 && this.a_lnks[i].length != 0) {
                document.write('<img class="rotatorclass showhand" src="' + this.a_items[i] + '"' + s_attributes + ' onclick="window.location.href =\'' + this.a_lnks[i] + '\';"' + ' id="tslide' + this.n_id + '_' + i + '" style="position:relative;z-index:-1;filter:alpha(opacity=100);" />');
                // document.write('<img class="rotatorclass" src="', this.a_items[i] , '"', s_attributes, ' name="tslide', this.n_id, '_', i, '" style="position:relative;z-index:-1;filter:alpha(opacity=100);" />');
            }
            else {
                
                document.write('<img class="rotatorclass" src="' + this.a_items[i] + '"' + s_attributes + ' id="tslide' + this.n_id + '_' + i + '" style="position:relative;z-index:-1;filter:alpha(opacity=100);" />');
            }
            this.a_imgRefs[i] = document.images['tslide' + this.n_id + '_' + i];
            this.a_imgRefs[i].style.marginLeft = '-' + this.a_tpl.width + 'px';
            this.f_slideOp(i, 0);
            this.a_imgRefs[i].style.zIndex = i;
        }

        // calculate transition variables
        this.n_timeDec = Math.round(this.a_tpl['transtime'] * 1e3 / this.a_tpl['steps']);
        this.n_opacDec = Math.round(100 / this.a_tpl['steps']);

        // run this sucker
        this.f_run();
    }

    function tslide_goto(n_slide, b_now) {

        // cancel any scheduled transitions	
        if (this.o_timerS) {
            clearTimeout(this.o_timerS);
            this.o_timerS = null;
            if (this.n_nextSlide) {
                this.f_slideOp(this.n_nextSlide, 0);
                this.n_nextSlide = null;
            }
        }

        // determine the next slide
        this.n_nextSlide = (n_slide == null ? this.n_currentSlide + 1 : n_slide) % this.a_items.length;
        if (this.n_nextSlide == this.n_currentSlide) return;

        // schedule transition
        this.o_timerS = setTimeout('A_SLIDES[' + this.n_id + '].f_fade' + (this.n_nextSlide > this.n_currentSlide ? 'In' : 'Out') + '()', (b_now ? 0 : this.a_tpl['slidetime'] * 1e3));
    }

    function tslide_fadeIn(n_opacity) {
        // new transition
        if (n_opacity == null) {
            n_opacity = 0;
        }
        n_opacity += this.n_opacDec;
        // end of transition
        if (n_opacity > 99) {
            this.f_slideOp(this.n_nextSlide, 99);
            this.f_slideOp(this.n_currentSlide, 0);
            this.n_currentSlide = this.n_nextSlide;
            this.n_nextSlide = null;
            return this.f_run();
        }
        // set transparency
        this.f_slideOp(this.n_nextSlide, n_opacity);

        // cycle
        this.o_timerT = setTimeout('A_SLIDES[' + this.n_id + '].f_fadeIn(' + n_opacity + ')', this.n_timeDec);
    }
    function tslide_fadeOut(n_opacity) {
        // new transition
        if (n_opacity == null) {
            n_opacity = 99;
            this.f_slideOp(this.n_nextSlide, 99);
        }
        n_opacity -= this.n_opacDec;
        // end of transition
        if (n_opacity < 0) {
            this.f_slideOp(this.n_currentSlide, 0);
            this.n_currentSlide = this.n_nextSlide;
            this.n_nextSlide = null;
            return this.f_run();
        }
        // set transparency
        this.f_slideOp(this.n_currentSlide, n_opacity);

        // cycle
        this.o_timerT = setTimeout('A_SLIDES[' + this.n_id + '].f_fadeOut(' + n_opacity + ')', this.n_timeDec);
    }

    function tslide_slideOp(n_slide, n_opacity) {
        if (!n_slide) return;
        var e_slide = this.a_imgRefs[n_slide];
        tslide_setOpacity(e_slide, n_opacity);
    }

    function tslide_randomize(a_source, a_slnks) {
        var a_items = [],
        a_links = [];
        while (a_source.length) {
            n_index = Math.ceil(Math.random() * a_source.length) - 1;
            a_items[a_items.length] = a_source[n_index] + "|" + a_slnks[n_index];
            a_source[n_index] = a_source[a_source.length - 1];
            a_slnks[n_index] = a_slnks[a_slnks.length - 1];
            a_source.length = a_source.length - 1;
            a_slnks.length = a_slnks.length - 1;
        }

       
        return a_items;
    }

   

    // cross-browser opacity
    var s_uaApp = navigator.userAgent.toLowerCase();
    if (s_uaApp.indexOf('opera') != -1 || s_uaApp.indexOf('safari') != -1)
        window.tslide_setOpacity = function (e_element, n_opacity) {
            e_element.style.opacity = n_opacity / 100;
        };
    else if (s_uaApp.indexOf('gecko') != -1)
        window.tslide_setOpacity = function (e_element, n_opacity) {
            e_element.style.MozOpacity = n_opacity / 100;
            e_element.style.opacity = n_opacity / 100;
        };
    else if (s_uaApp.indexOf('msie') != -1)
        window.tslide_setOpacity = function (e_element, n_opacity) {
            try { e_element.filters.alpha.opacity = n_opacity; } catch (e) { };
        };
    else
        window.tslide_setOpacity = null;

    // defaults
    var A_TSLIDEDEFS = [
	'steps', 40,
	'css', '',
	'transtime', 0.5,
	'slidetime', 2
];
</script>
</head>
<body>
 <script type="text/javascript">

     // configuration structure
     var A_TPL111 = {
         // randomize the array each time page loads
         'random': true,
         // number of transparency changes during the transition
         //	increase for smoother transition, reduce for less CPU usage
         'steps': 20,
         // transition duration in seconds
         'transtime': 1.5,
         // slide time in seconds
         'slidetime': 5,
         // width of the slide (optional)
         'width': 140,
         // height of the slide (optional)
         'height': 168,
         // alt text for the image (optional)
         'alt': 'alternate',
         // css class assigned to the slide <img /> (optional)
         'css': ''
     };

     // list of images to display
     var A_ITEMS111 = [
		'http://histochemicalsociety.org/Images/HomePage-RotatingGraphic-Award.jpg',
        'http://histochemicalsociety.org/Images/HomePage-RotatingGraphic-JHC.jpg',
        'http://histochemicalsociety.org/Images/HomePage-RotatingGraphic-Directory.jpg',
        'http://histochemicalsociety.org/Images/HomePage-RotatingGraphic-Meeting.jpg'
	];

    var A_LINKS = [
		'http://google.com',
		'http://msn.com',
		'http://yahoo.com',
		'http://bing.com'
		
	];



     // fader initialization	
    var mySlideShow111 = new tFader(A_ITEMS111, A_LINKS, A_TPL111);

</script>
</body>
</html>

Open in new window

0
Comment
Question by:guyriso
  • 3
  • 2
8 Comments
 
LVL 15

Expert Comment

by:Insoftservice
ID: 39808570
Try out this one.
Check right page of the below link for reference.
http://www.boisoc.com/


<html>
<head>
<title>Love to Marry free website</title>
<script type="text/javascript" src="http://boisoc.com/media/scripts/jquery-1.4.2.js" ></script>
</head>
<script type="text/javascript">

function theRotator() {
	//Set the opacity of all images to 0
	$('div.rotator ul li').css({opacity: 0.0});
	
	//Get the first image and display it (gets set to full opacity)
	$('div.rotator ul li:first').css({opacity: 1.0});
		
	//Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
	
	setInterval('rotate()',3000);
	
}

function rotate() {	
	//Get the first image
	var current = ($('div.rotator ul li.show')?  $('div.rotator ul li.show') : $('div.rotator ul li:first'));

    if ( current.length == 0 ) current = $('div.rotator ul li:first');

	//Get next image, when it reaches the end, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first'));
	


	//Set the fade in effect for the next image, the show class has higher z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1000);

	//Hide the current image
	current.animate({opacity: 0.0}, 1000)
	.removeClass('show');
	
};



$(document).ready(function() {		
	//Load the slideshow
	theRotator();
	$('div.rotator').fadeIn(1000);
    $('div.rotator ul li').fadeIn(1000); // tweek for IE
});
</script>
<style type="text/css">

ul{
	list-style-type:none;
}

/* rotator in-page placement */
    div.rotator {
	position:relative;
	height:250px;
/*	margin-left: 15px;
*/	display: none;
}
/* rotator css */
	div.rotator ul li {
	float:left;
	position:absolute;
	list-style: none;
}
/* rotator image style */	
	div.rotator ul li img {
	border:1px solid #ccc;
	padding: 4px;
	background: #FFF;
}
    div.rotator ul li.show {
	z-index:500
}
</style>


	<div class="rotator">
  <ul>
    <li class="show"><a href="http://treo.biz" target="_blank"><img src="http://boisoc.com/media/commitee/gal1.jpg" width="220" height="229"  alt="pic1" /></a></li>
    <li><a href="http://arts.treo.biz" target="_blank">
	<img src="http://boisoc.com/media/commitee/gal2.jpg" width="220" height="229"   alt="pic2" /></a></li>
    <li><a href="http://boisoc.com/gallery" target="_blank">
	<img src="http://boisoc.com/media/commitee/gal3.jpg" width="220" height="229"   alt="pic3" /></a></li>
    <li><a href="http://boisoc.com/holidayhome" target="_blank">
	<img src="http://boisoc.com/media/commitee/gal4.jpg" width="220" height="229"   alt="pic4" /></a></li>
 <li><a href="http://arts.treo.biz" target="_blank">
        <img src="http://boisoc.com/media/commitee/gal5.jpg" width="220" height="229"   alt="pic4" /></a></li>

  </ul>

</div>
</html>

Open in new window

0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39808616
Line 68, you've :
window.location.href =\'' + this.a_lnks[ 0 ]
instead :
window.location.href =\'' + this.a_lnks[ i ]

and replace :
for (var i = 1; i < this.a_items.length; i++) {
by :
for (var i = 0; i < this.a_items.length; i++) {

Test page : http://fiddle.jshell.net/Wycbz/show/
"Source" : http://jsfiddle.net/Wycbz/
0
 

Author Comment

by:guyriso
ID: 39822168
@insoftservice, I was trying to stay away from using jquery for this!

@leakim971, Your solution is rendering something similar to what was being rendered with the code I provided.  Everything renders the way you would expect it to, but when clicking on the images, the links are not corresponding to the image that is clicked.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 82

Expert Comment

by:leakim971
ID: 39823973
Did you tried my test page?
0
 

Author Comment

by:guyriso
ID: 39838977
@leakim971 - yes. Sorry it has taken me so long to respond.  I am not on the distribution list that receives these emails and my co worker forgot to forward them to me.  I will continue to monitor this thread so we can get this resolved so you can receive credit for your time.
0
 

Author Comment

by:guyriso
ID: 39868271
I tried the test page but the links do not match with the images being clicked.  Everything renders properly, but when you look at what image is being clicked, they are not matching with the associated links.

Thanks
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now