23 02 2013
Use jQuery Cycle2 to Toggle Background Images
I recently took on a side project for an old friend who wanted a website. I was a little hesitant at first but I eventually caved in and said I’d do it. I figure I get a lot of ideas from my boss at work and I have gained a lot of tips and tricks along the way that I can probably put something decent together.
The things about me is I have zero design sense. I can match colors very well but when it comes to making something look pretty, I would probably do a terrible job. This is also the number reason why I never design / build a wordpress theme for this blog. I’m a terrible web designer but I really think since I started working for the company I do, I’ve gained a better idea about what a professional designer would approve of and what they would absolutely say no to.
So what about toggling background images? I thought it could double as a gallery actually. The idea is the background sits at a dimmed out opacity. The user clicks on a button, and the content slides away and the background comes in at full opacity. The controls for the slideshow appear and what you have is a fully functional gallery. I can’t disclose the site I’m working on yet due to it not having a public facing URL. But, I can disclose what sort of tricks I’m trying to utilize. So here is how I’m doing the background using jQuery Cycle2.
I have a div which is my slideshow container that contains child divs inside which are forced to be 100% height. I then use jQuery Cycle 2 to cycle through each div.
<div id="slider" data-cycle-slides="> div.galleryImage" data-cycle timeout="3000" data-cycle-manual-speed="500" data-cycle-prev="#prev" data-cycle-next="#next">
<div class="galleryImage galleryImage1"></div>
<div class="galleryImage galleryImage2"></div>
Here’s the CSS I applied to make them 100% height.
background-size: 100% auto;
Then for each of my “slides”, I assign a unique class for each image i.e. “galleryImage1″, “galleryImage2″ which controls which image is being used as the background.
Then you loading in jQuery and jQuery Cycle 2. Here’s the snippet that initiates the slideshow:
So at this point it’s looking great. I then have a separate content div which I then absolutely position over my slideshow to make it look like fading backgrounds.
The advantages of using your images as a background versus a slideshow of images inside a div is that it makes your website much easier to browser. If I simply did divs containing images that were 100% width and 100% height, the image would still be selectable by the mouse and I just don’t think it would run as smoothy.
Plus, we’re using it as a background. It should be a background. :P
Edit: To accommodate for content that expands below the fold, I added a wrapper div around the slider and gave it fixed positioning. This is to keep the background in place so that you don’t get a big empty white spot when you need to scroll.
Demo: For a demo, check out http://www.sfspoon.com