Solved

Button image change on a timer

Posted on 2011-03-16
14
411 Views
Last Modified: 2012-05-11
In my project I need to update the Images on buttons dynamically using JQuery.
In my project I have a page which contains 5 image buttons laying horizantally.
When the page loads image on the  Button1  should change(remaining 4 buttons remains same).
After 3 seconds Button1 comes back to its original image and  image on Button2 will change.
After 3 seconds Button2 comes back to its original image and  image on Button3 will change.
And so on..
But After the Button5 is done , It should come back to the Button1 image again.
This should go on in a continuous loop.

I am able to do this (changing the image upto button5) with Jquery.
I am not able to put this in the loop(Its breaking after the Button5).
Any help will be appreciated.

@@@@@@@@@@@@@

<script type="text/javascript">
  $(document).ready(function (){
            rotateButton();
        });
        
		function rotateButton(){
                    rotateButton1(0);                    
                    rotateButton1off(3000);
                    rotateButton2on(3000);
                    rotateButton2off(6000);
                    rotateButton3on(6000);
                    rotateButton3off(9000);
                    rotateButton4on(9000);
                    rotateButton4off(12000);
                    rotateButton5on(12000);
                    rotateButton5off(15000);                     
                }

            
     function rotateButton1(delay){
        window.setTimeout(function(){
            $(".main-nav-button1").removeClass("main-nav-button1").addClass("main-nav-button1-on"); 
        }, delay);
     }
     function rotateButton1off(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button1-on").removeClass("main-nav-button1-on").addClass("main-nav-button1");           
         }, delay);     
     }
     function rotateButton2on(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button2").removeClass("main-nav-button2").addClass("main-nav-button2-on"); 
        }, delay);     
     }
     function rotateButton2off(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button2-on").removeClass("main-nav-button2-on").addClass("main-nav-button2"); 
        }, delay);     
     }
     function rotateButton3on(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button3").removeClass("main-nav-button3").addClass("main-nav-button3-on"); 
        }, delay);     
     }
    function rotateButton3off(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button3-on").removeClass("main-nav-button3-on").addClass("main-nav-button3"); 
        }, delay);     
     }
     function rotateButton4on(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button4").removeClass("main-nav-button4").addClass("main-nav-button4-on"); 
        }, delay);     
     }
     function rotateButton4off(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button4-on").removeClass("main-nav-button4-on").addClass("main-nav-button4"); 
        }, delay);     
     }
     function rotateButton5on(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button5").removeClass("main-nav-button5").addClass("main-nav-button5-on"); 
        }, delay);     
     }
     function rotateButton5off(delay){ 
        window.setTimeout(function(){
            $(".main-nav-button5-on").removeClass("main-nav-button5-on").addClass("main-nav-button5"); 
        }, delay);     
     }
</script>

Open in new window

0
Comment
Question by:ken_rgr
  • 10
  • 4
14 Comments
 
LVL 7

Accepted Solution

by:
nbove earned 500 total points
ID: 35152859
I just want to say that retrieving the buttons by their class name is a terribly brittle solution and should be replaced with getting them by their id or some other method.  With that being said this solution will probably work.  You will have to set the initial state of the 5th button to the "on" state.  As soon as you
start the rotation code, it will immediate flip the 5th button to the "off" state and flip the 1st to the "on" state and will continue the rotation indefinitely.
function BeginRotation() {
  rotateButton(0);
}
function rotateButton(var buttonIndex) {
  var previousIndex = (buttonIndex + 4) % 5;

  var previousCurrentClass = '.main-nav-button' + (previousIndex + 1) + '-on';
  var previousNewClass = '.main-nav-button' + (previousIndex + 1);
  var currentClass = '.main-nav-button' + (buttonIndex + 1);
  var newClass = '.main-nav-button' + (buttonIndex + 1) + '-on';

  $(currentClass).removeClass(currentClass).addClass(newClass);
  $(previousCurrentClass).removeClass(previousCurrentClass).addClass(previousNewClass);
  window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
}

Open in new window

0
 

Author Comment

by:ken_rgr
ID: 35153495
Hi Bove

Thanks for your solution.
I will try it tommorrow, and get back to you.

Once again really appreciated your time.
0
 

Assisted Solution

by:ken_rgr
ken_rgr earned 0 total points
ID: 35156968
Hi Bove

I tried your solution.
Unfortunately it seems its falling in infinite loop.
and after few seconds Image overlay comes to Button3 and stays there forever.
Its not moving form Button3.
It seems we are making slight mistake somewhere.
And One more thing I made small change to your code(Other wise its not working).

Any update will be appriciated.
Here is the updated code
And I called BeginRotation() function in
 $(document).ready(function (){}

Thanks for your time
function BeginRotation() {
          rotateButton(0);
        }
        function rotateButton(buttonIndex) {
          var previousIndex = (buttonIndex + 4) % 5;

          var previousCurrentClass = '.main-nav-button' + (previousIndex + 1) + '-on';
          var previousNewClass = '.main-nav-button' + (previousIndex + 1);
          var currentClass = '.main-nav-button' + (buttonIndex + 1);
          var newClass = '.main-nav-button' + (buttonIndex + 1) + '-on';

          $(currentClass).removeClass(currentClass).addClass(newClass);
          $(previousCurrentClass).removeClass(previousCurrentClass).addClass(previousNewClass);
          window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
    }

Open in new window

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.

 

Author Comment

by:ken_rgr
ID: 35159951
HI Bove

Any update ?
I appreciate your time .

Thanks
0
 
LVL 7

Expert Comment

by:nbove
ID: 35160232
You could try adding some alerts in the function to output the values of the different variables during the loop.

Add the following code after the variable declarations:
alert('Previous Current Class: ' + previousCurrentClass + '\nPrevious New Class: ' + previousNewClass + '\nCurrent Class: ' + currentClass + '\nNew Class: ' + newClass);

This will pop up a window and allow you to see what the different values of the variables are at different phases of the loop.

Let me know if this helps.
0
 

Author Comment

by:ken_rgr
ID: 35160676
Hi Bove

Its passing the correct values
But I am keep on getting alerts with updated values.
Its going in to infinite loop.
Its not letting me do anything
It didn't even allowed me to close the browser.
I had to close the browser from Task manager.

Any idea how to fix this.

Thanks for your time
alert.png
0
 

Author Comment

by:ken_rgr
ID: 35161290
Hi Bove

Any update on this one.
Its a kind of urgent for me.

Thanks for the help.
0
 
LVL 7

Expert Comment

by:nbove
ID: 35161301
Just a bit of trivia, you cannot close the browser while an alert dialog is open.  You have to close the alert first, then close the browser.  That is why you were having trouble.

The script is intended to run in an infinite loop.  I assumed this from the statement in your original post:
"This should go on in a continuous loop."

From my understanding of your post, it appears that the script is continuing to run indefinitely, which is good.  But it is not updating the buttons, which is bad.

I assume that the reason it is not updating the buttons is because there may be multiple buttons with the same class name.  But without seeing the HTML for the page, it is hard to say.
0
 

Author Comment

by:ken_rgr
ID: 35161427
Hi Bove

You are right. Script is continuously running and its not updating the buttons.
One more thing when I  clicked on the alert next alert showed up immediately
without 3 second delay. it happend for all the alerts(alerts showed immediately without any delay).
I have attached the html code .
Remember you wont see jquery librarys as they are in master page.

Thanks for your time and help.
<%@ Page Language="C#" MasterPageFile="~/test.master" Title="test" %>
<asp:Content ID="Content1" ContentPlaceHolderID="headercontent" Runat="Server">

<!-- begin main site container -->
<div id="site-container">

<script type="text/javascript">
		// Set up Sliders
		// **************
		$(function(){

			$('#slider1').anythingSlider({
				startStopped    : false, // If autoPlay is on, this can force it to start stopped
				width           : 1000,   // Override the default CSS width
				height          : 389,
				theme           : 'metallic',
				autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
				resumeDelay     : 3000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
				onSlideComplete : function(slider){
					// alert('Welcome to Slide #' + slider.currentPage);
				}
			});

		});
		
	
		
	</script>
	
	<!-- Top Image Rotator - set to 3 secs delay.   -->
	<script  type="text/javascript">
	
        var interval = 3000; // delay between rotating images (in seconds)
        var random_display = 0; // 0 = no, 1 = yes

        var image_index = 0;
        image_list = new Array();
        image_list[image_index++] = new imageItem("images/callout15.png");
        image_list[image_index++] = new imageItem("images/callout1.png");        
        image_list[image_index++] = new imageItem("images/callout2.png");
        
        var number_of_image = image_list.length;
        function imageItem(image_location) {
        this.image_item = new Image();
        this.image_item.src = image_location;
        }
        function get_ImageItemLocation(imageObj) {
        return(imageObj.image_item.src)
        }
        function generate(x, y) {
        var range = y - x + 1;
        return Math.floor(Math.random() * range) + x;
        }
        function getNextImage() {
        if (random_display) {
        image_index = generate(0, number_of_image-1);
        }
        else {
        image_index = (image_index+1) % number_of_image;
        }
        var new_image = get_ImageItemLocation(image_list[image_index]);
        return(new_image);
        }
        function rotateImage(place) {
        var new_image = getNextImage();
        document[place].src = new_image;
        var recur_call = "rotateImage('"+place+"')";
        setTimeout(recur_call, interval);
        }
        //  End -->
        
        
        
        $(document).ready(function (){
            var delay = 0;
            var t;
            rotateImage('rImage');
            BeginRotation();
           // rotateButton();

        });
        

     
     function BeginRotation() {
          rotateButton(0);         
        }
        function rotateButton(buttonIndex) {
          var previousIndex = (buttonIndex + 4) % 5;

          var previousCurrentClass = '.main-nav-button' + (previousIndex + 1) + '-on';
          var previousNewClass = '.main-nav-button' + (previousIndex + 1);
          var currentClass = '.main-nav-button' + (buttonIndex + 1);
          var newClass = '.main-nav-button' + (buttonIndex + 1) + '-on';
          
          // alert('Previous Current Class: ' + previousCurrentClass + '\nPrevious New Class: ' + previousNewClass + '\nCurrent Class: ' + currentClass + '\nNew Class: ' + newClass);

          $(currentClass).removeClass(currentClass).addClass(newClass);
          $(previousCurrentClass).removeClass(previousCurrentClass).addClass(previousNewClass);
              window.setTimeout(rotateButton((buttonIndex + 1) % 5), 3000);
        }

</script>

  <!-- begin header -->
  <div id="header">
    <div id="header-logo-area">
      <a href="Default.aspx"><img src="images/migraines-at-work-logo.jpg" id="migraines-at-work-logo" alt="Migraines at Work. Get the facts." /></a>
    </div>
    <div id="header-callout-area">
  
       <!-- AnythingSlider #1 -->
       <div id="header-callout">
			<img name="rImage" src="images/callout1.png">

		</div>
		<!-- END AnythingSlider #1 -->
		
    </div>
    <div id="header-top-right-area">
      <a href="#" target="_blank"><img src="images/like.jpg" width="56" height="26" alt="Like this on Facebook" /></a> &nbsp;
      <a href="#" target="_blank"><img src="images/print.jpg" width="43" height="27" alt="Print this page" /></a>
    </div>
    <div class="clearboth"></div>
  </div>
  <!-- end header -->

  <!-- begin homepage slideshow area -->
  
        <!-- AnythingSlider #1 -->
			<ul id="slider1">
				<li><a href="Default.aspx"><img src="images/home-slide1.jpg"alt="" /></a></li>
				<li><a href="identify.aspx"><img src="images/home-slide2.jpg" alt="" /></a></li>
				<li><a href="http://www.msn.com"><img src="images/home-slide3.jpg" alt="" /></a></li>
				<li><a href="http://www.facebook.com"><img src="images/home-slide4.jpg" alt="" /></a></li>
				<li><a href="http://www.nicotrol.com"><img src="images/home-slide5.jpg" alt="" /></a></li>
			</ul>  
		<!-- END AnythingSlider #1 -->
  <!-- end homepage slideshow area -->

  <!-- begin main nav area -->
 <div id="main-nav-container">
    <a href="test1.aspx" class="main-nav-button1"><span>Welcome</span></a>
    <a href="test2.aspx" class="main-nav-button2"><span>Identify Your Migraine</span></a>
    <a href="test3.html" class="main-nav-button3"><span>Discuss with Your Doctor</span></a>
    <a href="test4.html" class="main-nav-button4"><span>Treat Your Migraine</span></a>
    <a href="test5.html" class="main-nav-button5"><span>Important Resouces</span></a>
    <div class="clearboth"></div>
  
  
  <!-- end main nav area -->

  

</div>

</asp:Content>

Open in new window

0
 

Author Comment

by:ken_rgr
ID: 35161933
Hi Bove

Any update .

thank You
0
 

Author Comment

by:ken_rgr
ID: 35165743
HI Anybody there
I need little help here please...

Thank you
0
 
LVL 7

Expert Comment

by:nbove
ID: 35171838
The code assumes that there is always one button that is in the "On" state.  Since we are starting the rotation with the 1st button it will assume that the 5th was in the "On" state.
Try changing
<a href="test5.html" class="main-nav-button5"><span>Important Resouces</span></a>
to
<a href="test5.html" class="main-nav-button5-on"><span>Important Resouces</span></a>
0
 

Author Comment

by:ken_rgr
ID: 35193391
Hi nBove

I figured out the problem.
Your solution  is 99% correct.
There was small problem in calling the rotateButton() function.
I will accept your code as solution .
Once again thanks for your time and help.

Here is the change I made
@@@@@@@@@@@@@

 window.setTimeout("rotateButton(" + ((buttonIndex + 1) % 5) + ")", 3000);
@@@@@@@@@@@@@
0
 

Author Closing Comment

by:ken_rgr
ID: 35225442
the solution provided by nBove is 99% correct .
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
This article discusses how to create an extensible mechanism for linked drop downs.
In this tutorial viewers will learn how to customize the background color and font color of highlighted text using the ::selection element in CSS Begin by defining the selected text as an element in CSS by typing "::selection": Style the ::selection…
The viewer will learn how to dynamically set the form action using jQuery.

803 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