Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

I was working on a problem where I needed to change the text in a menu to be the name of the department, then the phone number to the department. Both of which had to be a link to the department’s page. I figured that this would be very easy in JQuery. It took a bit of time, but I figured out a fairly easy solution. I figured out a few things along the way.

  • fadeIn, fadeOut, fadeTo only change opacity
  • calling .html on an item that was faded-out immediately makes it visible

The final solution involved making an array that held the two sets of html for the menu item. I incremented a counter and modded by the number of items in the array to get the next one to display. Then I faded out the anchor tag within the item, changed the html of the now faded anchor to some html that was set to display:none, then faded in the anchor within the list item. I surrounded that with a set interval.

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var menuText = ['<a href="/...." style="display:none;" title="My Title">Department Name</a></li>',   // first menu item html
                            '<a href="/...." style="display:none;" title="My Title">Phone Number</a></li>'];     // second menu item html
            var menuItem = 0;

            setInterval(function() {
                menuItem = ++menuItem % 2;  // 0 or 1

                $("#myTarget a").fadeOut(1000);  // 1 second
                $("#myTarget").html(menuText[menuItem]);  // change the html to be new html that is set to hidden
                $("#myTarget a").fadeIn(1000);   // 1 second
            }, 4 * 1000);  // 4 seconds - ensure that this is longer than the fade out/in duration
        });
    </script>
</head>
<body>
    <ul>
        <li>list item 1</li>
        <li>list item 2</li>
        <li>list item 3</li>
        <li id="myTarget"><a href="/...." title="My Title">Department Name</a></li>  // start with the initial value
        <li>list item 4</li>
        <li>list item 5</li>
    </ul>
</body>
</html> 

March 7th, 2011

Posted In: JQuery

Leave a Comment

LinkedIn Auto Publish Powered By : XYZScripts.com