Home > CSS Help > SkillShare Forum – CSS Beauty – jquery: rotating css file using a …

SkillShare Forum – CSS Beauty – jquery: rotating css file using a …

March 19th, 2009

SkillShare Forum – CSS Beauty – jquery: rotating css file using a …



JavaScript / DOM / AJAX: jquery: rotating css file using a setinterval, problem with ie … only shows up if the screen is in view when the css swap happens. …

Source


Similar Posts

    A Simple jQuery Stylesheet Switcher

    jQuery stylesheeet switcher

    There are lots of reasons you might want to offer your users more than one CSS file for your website:

    • You want to offer a “stylish” low-contrast and an easy-to-read high-contrast version of your site.
    • You have many low-vision readers and want to give them easy access to a customized stylesheet with a larger typeface.
    • Your site is schizophrenic and you want to be able to change the look quickly.

    Whatever the reason, it’s amazingly easy to create a function that swaps between multiple stylesheets using jQuery.

    The first step of course is to build several different CSS files, which we’ll then swap between. Once that is done, we can dive into the XHTML and jQuery that makes the magic happen.

    The XHTML

    First, we need to create a set of links that will allow the user to swap between CSS files. You can make this as simple or as fancy as you’d like. For the sake of brevity, my links are simple:

    <ul id="nav">
    	<li><a href="#" rel="/path/to/style1.css">Default CSS</a></li>
    	<li><a href="#" rel="/path/to/style2.css">Larger Text</a></li>
    	<li><a href="#" rel="/path/to/style3.css">Something Different</a></li>
    </ul>

    Here I have three links, each with a “rel” attribute indicating which CSS file the link will load. Technically, I could have just as easily put this information in the “href” attribute, but I didn’t want to for one specific reason: if the user has JavaScript disabled and the CSS file is listed in the href, then clicking the link will send the user to the CSS file directly (not loading it like we intended). But our way, if JS is disabled, the user gets nothing at all: which is certainly preferable to the less savory alternative.

    The jQuery

    Like I promised, the jQuery is really simple:

    $(document).ready(function() {
    	$("#nav li a").click(function() {
    		$("link").attr("href",$(this).attr('rel'));
    		return false;
    	});
    });

    This function waits until the document is loaded (generally an important step when interacting with the DOM), then attaches a click function to each of our nav anchors. The function basically says, “when someone clicks on this link, replace the link (stylesheet) tag’s href attribute with the contents of this link’s rel attribute.” The “return false” at the end just stops the browser from trying to follow the link.

    Of course, you might have to get more detailed if you have more than one link tag, for example, but that’s easily done by giving the link tag a class (”changeme,” for argument’s sake), and writing something like this:

    $("link.changeme").attr("href",$(this).attr('rel'));

    And while this stylesheet switcher is already complete, we might want to give it some memory: after all, your users might get annoyed if they have to switch their styles back to their preferences every time they visit your site. For that, we’ll need to set a cookie. And to make that easier, I’ll use the jQuery cookie plugin (which I’ve talked about previously when building a popout ad).

    With the plugin loaded, we can modify our jQuery thusly:

    $(document).ready(function() {
    	if($.cookie("css")) {
    		$("link").attr("href",$.cookie("css"));
    	}
    	$("#nav li a").click(function() {
    		$("link").attr("href",$(this).attr('rel'));
    		$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
    		return false;
    	});
    });

    Now we have two statements. The first one checks as soon as the page is done loading to see if a cookie called “css” has been set. If so, it sets the stylesheet to be the one indicated in that cookie. Otherwise, it does nothing.

    Our click function is much the same, except after we set the stylesheet, we also set a cookie. This cookie doesn’t expire for an entire year (and each time the user changes their stylesheet preferences, it would reset this timer), giving them a good 365 of CSS bliss.

    Fine Tuning

    There is one minor annoyance with this stylesheet switcher: there’s generally a flash of the “default” CSS when the user loads the page. That’s because the script waits until the document is “ready” before switching the link’s href. There is a way around this: moving the first “if” statement outside of the document ready function, like so:

    if($.cookie("css")) {
    	$("link").attr("href",$.cookie("css"));
    }
    $(document).ready(function() {
    	$("#nav li a").click(function() {
    		$("link").attr("href",$(this).attr('rel'));
    		$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
    		return false;
    	});
    });

    Generally speaking, you don’t want to run any jQuery until your document is ready. However, so long as your jQuery comes after your link tag in your document structure, like shown below, this shouldn’t be a major concern:

    <link rel="stylesheet" type="text/css" href="style1.css" />
    <script type="text/javascript" language="javascript" src="jquery.js"></script>
    <script type="text/javascript" language="javascript" src="jquery.cookie.js"></script>
    <script>... your jQuery goes here...</script>

    This means your jQuery will run before the document is done loading, and thus your link tag’s href will be swapped before your CSS has been applied. As I said before, it’s generally a bad idea to manipulate the DOM before document ready, but because we know the exact tag we want to manipulate and can place our jQuery below it in the DOM, we should be safe in this one specific instance.

    Here’s an example if you would like to see this technique in action.

    Read More

    Advanced jQuery Tabbed Box Techniques

    animated tabbed box interface

    Last week’s article covered how to build a tabbed box interface, starting with Photoshop, and moving through XHTML and CSS to our basic jQuery functionality. If you missed it, I would highly recommend starting your reading there. This article will show you how to use jQuery to make your tabbed interface more attractive and interactive. Specifically, I’ll show you how to:

    • Make your tabs all the same height
    • Automatically rotate through your tabbed content
    • Stop the rotation when the user is interacting with the content

    Equal Height Tabs

    The tabbed interface we built last week was fully functional, but one nicety I’d like to add is the option to have all your tabs be the same height – a height that is determined by the content within the tabs, not any number I arbitrarily determine in advance.

    While there are several ways to calculate and apply height in jQuery, the fastest and easiest means to our end would be to use the equalHeights jQuery plugin I developed and wrote about recently. By using that plugin, we’d only have to make a single addition to the “document ready” portion of our jQuery:

    $(".tabbed-content").equalHeights();

    This will cycle through all of our tabbed content divs and equalize their heights based on the height of the tallest div. The benefit of this is the content around our tabbed box won’t shift up or down each time the user switches tabs, resulting in a more pleasant visual experience.

    Rotate Through Tabbed Content

    While tabbed boxes like the one we’ve built are a great way to fit a large amount of content in a small space, they do have one drawback: many users never click through the tabs to see what all is offered, meaning they only ever see the content on the first tab. My proposed solution to this problem is to automatically rotate through the tabs.

    This solution has two benefits: first, the movement is more likely to catch the users’ eyes, increasing the chances they’ll notice the tabbed box in the first place. Second, it allows your users to see all the content your box contains instead of just the first tab.

    Making this adjustment to our jQuery requires edits in several areas, so I’ll show you the new code in its entirety before explaining what it all does:

    var currentTab = 0;
    var rotateSpeed = 5000;
    var numTabs;.
    var autoRotate;
    
    function openTab(clickedTab) {
    	var thisTab = $(".tabbed-box .tabs a").index(clickedTab);
    	$(".tabbed-box .tabs li a").removeClass("active");
    	$(".tabbed-box .tabs li a:eq("+thisTab+")").addClass("active");
    	$(".tabbed-box .tabbed-content").hide();
    	$(".tabbed-box .tabbed-content:eq("+thisTab+")").show();
    	currentTab = thisTab;
    }
    
    function rotateTabs() {
    	var nextTab = (currentTab == (numTabs - 1)) ? 0 : currentTab + 1;
    	openTab($(".tabbed-box .tabs li a:eq("+nextTab+")"));
    }
    
    $(document).ready(function() {
    	$(".tabbed-content").equalHeights();
    	numTabs = $(".tabbed-box .tabs li a").length;
    
    	$(".tabbed-box .tabs li a").click(function() {
    		openTab($(this)); return false;
    	});
    
    	autoRotate = setInterval("rotateTabs()", rotateSpeed);
    	$(".tabbed-box .tabs li a:eq("+currentTab+")").click()
    });

    The first variable, currentTab, is unchanged from our first iteration. But then we’ve added three new variables:

    • rotateSpeed is the number of milliseconds to wait before switching tabs.
    • numTabs is a variable that will contain the total number of tabs in our box. We’re initializing it at the beginning so we can use it in all our functions.
    • autoRotate is a variable we’ll use later.

    Our openTab function hasn’t changed. If you’d like to understand how it works, please refer to the first article.

    Next we’ve written a new function called rotateTabs. This function will handle the math required to determine which tab should be opened next. First we set a new variable, nextTab. What we set nextTab to depends on which tab we’re on currently. The function looks at currentTab: if currentTab is our last tab in the list, it starts back over at the beginning (the tab with an index of 0). Otherwise, nextTab is simply the next tab in the list. Once we’ve determined our next tab, we call the openTab function, which prevents us from having to duplicate all that heavy lifting.

    We’ve added two lines to our document ready function. The first sets the numTabs variable to be the number of tabs in our box. We don’t populate this variable until the document is ready, because otherwise it will try to count the tabs before our tabs have loaded and will return a length of -1 (aka, none found).

    The second bit we added is towards the end, where we set autoRotate. In autoRotate we’re calling the JavasScript setInterval function, which executes a piece of JavaScript on a regular interval. As we’ve written it, we will be calling our autoRotate function every “rotateSpeed” milliseconds. This means that when our document loads, it will wait that many milliseconds, then switch to the next tab, then pause again, then switch again infinitely.

    Pretty neat, huh? You can see this functionality in action here.

    Stopping the Rotation

    Now, automatically rotating your tabs is a pretty awesome effect, but at some point you’re probably going to want that rotation to stop. Specifically, you don’t want your tabs switching when your users are interacting with them.

    I tested several scenarios on when and how to stop the tabs from rotating before deciding on how I’m doing it here. It only requires editing a couple of lines from our document ready function:

    $(document).ready(function() {
    	$(".tabbed-content").equalHeights();
    	numTabs = $(".tabbed-box .tabs li a").length;
    	$(".tabbed-box .tabs li a").click(function() {
    		openTab($(this)); return false;
    	});
    	$(".tabbed-box").mouseover(function(){clearInterval(autoRotate)})
    	.mouseout(function(){autoRotate = setInterval("rotateTabs()", rotateSpeed)});
    
    	$(".tabbed-box .tabs li a:eq("+currentTab+")").click()
    	$(".tabbed-box").mouseout();
    
    });

    Here we’ve replaced our setInterval function with something a little more complex. We’re now using both setInterval and clearInterval (which stops setInterval), and we’re applying them when the user’s mouse interacts with our tabbed box.

    Specifically, we’re letting the box auto-rotate whenever the mouse is nowhere near the box, and stopping the box from rotating whenever the mouse is over the box. This means that as long as the user has the mouse over the box, as if they were reading, or clicking through the tabs, or clicking on something inside one of our tabs, the tabs wouldn’t switch on them. But as soon as they’re done interacting with the box, it’ll switch back to its regular rotation.

    This does require one extra line at the end of the script, to force a “mouseout” event on the tabbed box, which gets things rotating by default.

    You can see our fully functional tabbed interface here. Give it a try: watch it rotate through, and then try interacting with the box a bit. You’ll see that the tabs don’t automatically move, as long as you’re actively engaged with the box.

    And that’s that! I hope you’ve found this mini-series helpful, and I’d love to see how you’ve implemented this idea on your own websites. Drop me a line in the comments below if you do.

    Read More

    CSS at the Bottom

    Make sure to view this page in IE to see the blank white screen problem. Current time: 06:38:23. In this example the stylesheet’s LINK tag is included at the bottom of the document …

    Source

    Running jQuery with Other Frameworks Via noConflict

    Photo "Chess" by Romainguy. Used under a Creative Commons license.

    While jQuery is certainly a popular JavaScript framework, it’s by no means the only game in town. Other frameworks such as Prototype, MooTools, Dojo and many others all have their own strengths, weaknesses, and devoted groupies.

    Generally speaking, these frameworks all play well together — you can mix and match framework functionality to your heart’s content, as long as you don’t mind the additional overhead of loading several libraries simultaneously. So you have a calendar widget in jQuery that you love, but you’re already using Prototype to animate your navigation bar? Don’t be shy… use both!

    Of course, every once in a while you can run in to problems when combining JS frameworks — particularly (in my experience) when combining jQuery and Prototype. Luckily, jQuery was kind enough to provide us with a workaround.

    The Problem: Sharing Syntax

    The most common compatibility problem stems from both jQuery and Prototype using the same shortcut syntax: namely, the $().doSomething syntax. Here’s a sample line of code in jQuery:

    $('#myelement').addClass('active');

    And the same functionality in Prototype:

    $('myelement').addClassName('active');

    Note the basic similarity? Both frameworks claim the dollar sign notation for themselves, which can wreak havoc on snippets of code dropped willy-nilly into a website. If your jQuery code is grabbed up by Prototype, things will stop working fast. And similarly, if your Prototype code is snagged by jQuery, not even the awesome power of jQuery will be enough to overcome the code confusion.

    The Solution: noConflict Mode

    But not to worry! jQuery has provided us with a workaround called “noConflict mode.”

    By default, there are two equally correct ways to call a jQuery function — the dollar sign notation, and “jQuery” notation:

    $('#myelement').show();
    jQuery('#myelement').show();

    Both of the lines above do exactly the same thing. However, most people use and prefer the dollar sign notation. Why? Probably because it’s shorter, and if web developers didn’t care about brevity in their code, they probably wouldn’t have used a framework in the first place.

    Of course, just using the longer jQuery notation isn’t enough. If jQuery has already claimed the dollar sign for itself, any Prototype functionality relying on that notation will still be grabbed by jQuery.

    This is where the noConflict function comes in handy. Simply run the following line after both Prototype and jQuery have been loaded:

    jQuery.noConflict();

    This will cause jQuery to give up the dollar-sign notation, allowing the other library to take it over. And you can still use your jQuery snippet, provided you change all instances of $() to jQuery().

    Keeping it Short

    The noConflict mode does have one other bit of functionality that I’ve found useful in some of my projects: you can select a different variable to use instead of the standard “jQuery”. The usage looks like this:

    var $j = jQuery.noConflict();

    Now in addition to using the default jQuery() notation, I can also use the shorter $j() notation. This allows me to avoid running into problems with other frameworks, while still enjoying almost the same conciseness in my code.

    Read More

    CSS Rollover Buttons

    Our CSS button allows for both a graphical image to swap based on mouse state … This is a common problem for many CSS buttons and no preloading of images will help. …

    Source

    Projectseven.com – Dreamweaver Extensions: Swap Class

    … CSS – swapClass by PVII to open the interface. Select a Swap From class. … This listing shows all of the CSS class names that are on your page or defined …

    Source

    beta.eku.edu URLs

    … rotating/3.gif |====+====+rotating/6.gif |====+====+includes/basic7a.css |====+====+rotating/7.gif |====+====+rotating/9.gif …

    Source

    Accessible Header Images With CSS And XHTML [CSS Tutorials]

    You know content in header images isn’t accessbile by, for instance, those using a screen reader. But do you know how to get around the problem? Douglas uses CSS …

    Source

    Accessible Header Images With CSS And XHTML [CSS Tutorials]

    You know content in header images isn’t accessbile by, for instance, those using a screen reader. But do you know how to get around the problem? Douglas uses CSS …

    Source

    Survey For People Who Make Websites 2008 Results Out

    Back in 2007, the staff of A List Apart and An Event Apart conducted a survey and presented 37 questions to 33,000 web professionals, providing “the first data ever collected on the business of web design and development as practiced in the U.S. and worldwide” (ALA 2007 results). The results were compiled into a downloadable PDF file.

    In 2008 they did it again, the results of the 2008 Survey For People Who Make Websites are now out for public consumption. The survey had less respondents compared to the one held in 2007 down to 30,055. Data analysis is provided by Alan Brickman and Larry Yu. The results speak can be overwhelming for some. Thankfully the findings are presented in a friendly, easy to read article with clear and beautiful CSS Charts.

    ALA has generously shared the raw data with the community, which is available as tabbed text, CSV, and Excel spreadsheet. RAW data is a powerful thing, and I just have a couple of suggestions how it can be used:

    • AJAX application that allows visitors to enter their own responses, and generates a graph that shows where the respondent is in relation to others
    • Quick summary that shows the highest and lowest result per question
    • AJAX application that allows visitors to filter, sort, and sift through the data
    • Side-by-side comparison of 2008 and 2007 data

    All in all, big props to the ALA team for the tremendous effort spent on this endeavor. It is a great contribution to the web community. Looking forward to the 2009 survey!

    Share

    Read More