jQuery | Techerator https://techerator.com Techerator is an excellent source of tips, guides, and reviews about software, web apps, technology, mobile phones, and computers. Fri, 11 Mar 2011 17:38:20 +0000 en-US hourly 1 https://wordpress.org/?v=7.0.2 7158109 How To: Make a CSS background slideshow with jQuery https://techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-make-a-css-background-slideshow-with-jquery https://techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/#comments Tue, 02 Nov 2010 13:45:05 +0000 http://44.229.110.106/?p=9879 If jQuery has one strength, it’s the library’s fantastic ability to manipulate HTML objects. Built into the library are easy to use methods for moving objects, adjusting CSS and tag attributes, changing visibility of anything on the page, and many more. To sweeten the deal, jQuery includes animation effects that allow you to transition any […]

The post How To: Make a CSS background slideshow with jQuery first appeared on Techerator.

]]>
If jQuery has one strength, it’s the library’s fantastic ability to manipulate HTML objects. Built into the library are easy to use methods for moving objects, adjusting CSS and tag attributes, changing visibility of anything on the page, and many more. To sweeten the deal, jQuery includes animation effects that allow you to transition any object from one state to another in an aesthetic way that only takes a line or two of code.

With these ideas in mind, it’s a small wonder that many jQuery plugins were developed with the intention of easily introducing pretty slideshows to display and rotate series of images. However, if you look around long enough, you’ll be facing a frustrating truth—almost none of these slideshow plugins utilize the idea of rotating CSS backgrounds.

Right now you may be telling yourself, “Self, using rotating CSS backgrounds instead of image tags for a jQuery slideshow is a bad idea.” Well, surprise, this article is a dream within a dream within a dream to convince you of the opposite. When you wake up, you’ll have a changed mind, and better yet, you’ll think it was your idea.

Best practices in HTML, CSS, and Javascript

Let’s have an honest discussion about HTML markup and Javascript. As CSS became a dominant force in shaping the appearance of valid HTML in the 2004 and on, it became more important to structure markup in a meaningful way. Using tables for layout has gone the way of the dinosaurs, DIV overload is now taboo, and designers are utilizing more intelligent information structure in their markup. Somewhere in all this sanity, jQuery has made us a little bit crazy.

“Look how easy it easy to create an image slider for my page’s mast head!”

“But Brian, isn’t it foolish to make a mast head’s appearance reliant on an image tag rather than CSS?”

“Shut up, Self, just look at these animation effects. It’s so easy!”

“But Brian, what if you have 10 different images for a single mast head and jQuery doesn’t load properly or the user has Javascript disabled? Your page is going to look really funny with 10 versions of your mast head all displayed at the same time.”

“…screw those users…”

“This is not good practice, Brian.”

“But… but…”

“BE A CHAMPION!”

You get the idea. It’s not a good idea to use an image tag slider unless you’re looking for an alternative way of displaying structured content, such as a photo gallery. However, many designers use these convenient image sliders to display graphics better suited for CSS background use. Slackers.

Fear not, you can have your cake and eat it, too. All you need is jQuery and a bit of know-how. I’m here to provide the know-how, good buddy. Let’s do this—high five!

Creating an CSS background slider with jQuery

Step 1: Markup

We’ll start with the HTML markup and CSS. Our example will be a typical mast head that is of a fixed width and height in the body of the page:

[code lang=”xml”]

<div id="mast-head" style=”background: url(path/to/images/1.jpg) no-repeat; height: 300px; width: 300px;"></div>

[/code]

As always, we’ll include the jQuery library and provide a space for our Javascript code in the head of the page:

[code lang=”javascript”]

<script type="text/javascript" src="path/to/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//code goes here
});
</script>

[/code]

The line of code $(document).ready(function(){}) is a way of telling your page to execute commands after the page has finished loading. Our script will go inside, just to be sure that our code doesn’t try to manipulate HTML objects that have not yet loaded.

Step 2: Preloading Images

One pitfall of dynamic CSS backgrounds is that when a background image is changed, the user will notice a ‘flicker’ as the new background is loaded on the page. We can avoid unintended visual discrepancies by preloading the images before the background-changing code that is executed.

[code lang=”javascript”]

var imgArr = new Array( // relative paths of images
‘path/to/images/1.jpg’,
‘path/to/images/2.jpg’,
‘path/to/images/3.jpg’,
‘path/to/images/4.jpg’
);

var preloadArr = new Array();
var i;

/* preload images */
for(i=0; i < imgArr.length; i++){
preloadArr[i] = new Image();
preloadArr[i].src = imgArr[i];
}

[/code]

Let’s break it down. First, we create an array that holds the relative paths to each image file that we want to include in our rotation. Next, we create another array which will hold Image objects. A Javascript Image object is a symbol of an HTML image element, and once you declare its source, it is cached by the browser. We can then create a loop that goes through our ‘relative path’ array and creates an Image object representing each image we want in our rotation. The source is assigned for each Image object, and viola, our CSS background images are preloaded and cached.

Step 3: Dynamic CSS changes and animation

All that’s left is to take our preloaded CSS background images and rotate them one at a time over a set interval. This can be accomplished with a small amount of code:

[code lang=”javascript”]

var currImg = 1;
var intID = setInterval(changeImg, 6000);

/* image rotator */
function changeImg(){
$(‘#mast-head’).animate({opacity: 0}, 1000, function(){
$(this).css(‘background’,’url(‘ + preloadArr[currImg++%preloadArr.length].src +’) top center no-repeat’);
}).animate({opacity: 1}, 1000);
}

[/code]

There isn’t a lot of code, but there is a lot going on here. First, we set a variable that will map which image in the ‘preloaded’ array is being displayed. Next, we set the interval at which our changeImg() function is executed. Remember, Javascript measures time in milliseconds, so our argument of 6000 is equal to 6 seconds.

Finally, we create the changeImg() function that will change the CSS background image of the element we dictate while animating the process.  The logic is to use jQuery’s animate() method to transition from one CSS state to another over a set amount of time. In our case, we’re changing the opacity to 0 over a 1 second period. Then, we change the background image of the #mast-head element with jQuery’s css() function and a bit of fancy array element selection. At the end, we again use animate() to bring the element’s opacity back to 1. Essentially—fade out, change background, fade in. Neato!

Here’s how your final script will look:

[code lang=”javascript”]

<script type="text/javascript" src="path/to/js/jquery.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){

var imgArr = new Array( // relative paths of images
‘path/to/images/1.jpg’,
‘path/to/images/2.jpg’,
‘path/to/images/3.jpg’,
‘path/to/images/4.jpg’
);

var preloadArr = new Array();
var i;

/* preload images */
for(i=0; i < imgArr.length; i++){
preloadArr[i] = new Image();
preloadArr[i].src = imgArr[i];
}

var currImg = 1;
var intID = setInterval(changeImg, 6000);

/* image rotator */
function changeImg(){
$(‘#masthead’).animate({opacity: 0}, 1000, function(){
$(this).css(‘background’,’url(‘ + preloadArr[currImg++%preloadArr.length].src +’) top center no-repeat’);
}).animate({opacity: 1}, 1000);
}

});
</script>

[/code]

True to form, this jQuery demo has a lot of things happening in a small amount of space.  Use this portable little script for any number of projects, and remember, only use an image tag slider if it makes sense to do so! In many cases, dynamic CSS background changes are best practice. Check out this script in action.

Until next time, amigos, happy programming.

*kick*

The post How To: Make a CSS background slideshow with jQuery first appeared on Techerator.

]]>
https://techerator.com/2010/11/how-to-make-a-css-background-slideshow-with-jquery/feed/ 39 9879
How to Perform Age Verification with jQuery and Cookies (mmm, cookies) https://techerator.com/2010/09/how-to-perform-age-verification-with-jquery-and-cookies-mmm-cookies/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-perform-age-verification-with-jquery-and-cookies-mmm-cookies https://techerator.com/2010/09/how-to-perform-age-verification-with-jquery-and-cookies-mmm-cookies/#comments Fri, 03 Sep 2010 18:20:50 +0000 http://44.229.110.106/?p=8541 If you’re a freelance developer, chances are good that you’ll encounter a situation where you’ll have to make some content “off limits” to the kids. In most cases, such as with alcohol-related material, this is required by law. So, how do you do it? Well, if you’re using jQuery, the answer is “easily.” The first […]

The post How to Perform Age Verification with jQuery and Cookies (mmm, cookies) first appeared on Techerator.

]]>
End of the line, kiddies.

If you’re a freelance developer, chances are good that you’ll encounter a situation where you’ll have to make some content “off limits” to the kids. In most cases, such as with alcohol-related material, this is required by law. So, how do you do it? Well, if you’re using jQuery, the answer is “easily.”

The first thing that may jump to your mind is that Javascript is not fail-safe. This is true; all a user needs to do is disable Javascript in his or her browser, and any sort of Javascript-based security measure is rendered useless. Luckily, legal requirements for online age verification recognize this and acknowledge that it is entirely (at least for now) dependent on the honor of the user. However, if your particular situation requires a verification system that is a bit more robust, consider using sessions which are supported in both ASP and PHP.

In this example, I will illustrate a scenario where the user is prompted with the question “Are you at least 18 years of age?” Of course, this tutorial can be extended to prompt the user for specific birth dates. For this tutorial, you will need:

I’m going to let you download those as I go grab a coffee. Are we ready? OK, let’s roll.

Before anything else, we’ll need to create two pages: one will be the “verification” page while the other will represent every page that has an age restriction in place. In both pages we’ll need to include a relative link to the two jQuery files that will be handling the cookies. Look at the snippet below and copy/paste it within the <head> region of each page.

[code lang=”xml”]

<script type="text/javascript" src="[pathtofiles]/jquery.js"></script>
<script type="text/javascript" src="[pathtofiles]/jquery.cookie.js"></script>

[/code]

As with most jQuery solutions, you’ll need to add a <script> tag to your <head> region which will be used as a programming space.

[code lang=”php”]

<script type="text/javascript">
$(document).ready(function(){

//code goes here!

});
</script>

[/code]

Let’s start off with the “content” pages that are presumably age restricted. The script is actually quite simple. If a cookie is set that indicates the viewer is of legal age, nothing happens. Otherwise, the viewer is redirected to a “verification” page, and the intended page is stored as a URL variable. Nothing too complicated there.

[code lang=”javascript”]

if ($.cookie(‘is_legal’) == "yes") {
//legal!
} else {
document.location = "http://www.domain.com/[pathtofile]/verify.php?redirect=http://<?php echo $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; ?>";
}

[/code]

Let’s move on to the “verification” page. In this example, the user will be presented a “yes/no” question about their age. If they are of appropriate age, they click “yes” and are redirected to the page they intended to view. If they click “no”, they are redirected to a Google Images search for “puppies.” Isn’t that cute?

The trick here is that the “verification” page will need to be able to tell which page the user is intending to view. In some cases, the user may be clicking a link to a blog post, and then the age verification screen rudely interrupts his or her experience. When users verify their age, they want to be redirected back to the page they wanted to see, not just the homepage! So how do we accomplish this?

[code lang=”php”]

$(‘#accept-btn’).click(function(){
$.cookie(‘is_legal’, ‘yes’, { expires: 1, path: ‘/’, domain: ‘domain.com’ });

<?php if ( !isset($_REQUEST[‘redirect’]) || $_REQUEST[‘redirect’] == "" ) { ?>
document.location = "http://www.domain.com";

<?php }else{ ?>
document.location = "<?php echo $_REQUEST[‘redirect’]; ?>";
<?php } ?>
});

[/code]

We’ve set an ID to the “yes” button, which evokes some processing logic when it is clicked. Immediately a cookie is set named “is_legal” and the value “yes” is assigned to it. The other parameters dictate that the cookie will expire in 1 day, will be stored locally in the root of the cookie folder on the user’s machine, and is valid for the entire domain. For a more thorough explanation of jQuery Cookie’s parameters, check out the documentation.

You may be thinking “Hey, what’s the deal with the PHP stuff?” Well, PHP is very good at extracting URL variables, which we set on the “content” page. If you don’t have access to PHP on your server, you can do the same thing with Javascript, it’s just a little more involved (see a snippet). Our script determines if a redirect location was set and sends the user to the appropriate page.

That’s it—follow these steps and you’ll be keeping kids out of your age-restricted pages in no time. Well, that probably isn’t true, but you WILL be abiding by the law as a website administrator. For a look at this script in action, it is the current implementation at edwinton.com.

Happy programming!

The post How to Perform Age Verification with jQuery and Cookies (mmm, cookies) first appeared on Techerator.

]]>
https://techerator.com/2010/09/how-to-perform-age-verification-with-jquery-and-cookies-mmm-cookies/feed/ 12 8541