Archive for jQuery / Javascript

How Can I Make a Div Slider that is iPad Friendly?

There are a lot of sliders that can cycle through content that will work on the iPhone.  Many of these being powered by some kind of jQuery plugin.  However, I only found one that will actually include the functionality for the iPad to be able to use it’s swipe based interface. (click and drag to see more content)

Here is a link to the jQuery Simple iPhone-Slide plugin.  It has an excellent tutorial for such an awesome plugin.

http://jquery.hinablue.me/jqiphoneslide/

After including all the needed files, setting up the slider was as easy as the following function.  This is what I used for initialization:

$(document).ready(function() {
 
	$('#album').iphoneSlide({
		handler: "#slidePaging",
		pageHandler: ".slidePage",
		nextPageHandler : '.nextPage',
		prevPageHandler : '.prevPage',
		autoPlayTime: 9000,
		bounce: false,
                autoPlay: false,
		pager: {
	        pagerType: "dot",
	        selectorName: ".banner_pager",
	        childrenOnClass: "on",
	        slideToAnimated: true
	        },
		autoCreatePager: true,
                onShiftComplete: function(elem, page) {
                }
	});
});

Using FancyBox to display an element’s dynamic content

I’ve been trying to find a nice modal/lightbox for jquery and I was recommended FancyBox. But what I needed it for was not wholly described in their examples. I needed to get some json from an ajax call, parse the data into some HTML and set that HTML to a div that would pop up in FancyBox.

function getData(id)
{
	$.post('/test', "id="+id, function(data){ $('#popup').html(generatePopup(data));});
}

That will get my json and the generatePopup function would create some content and set it to the #popup div.

I made sure to put the #popup div inside another hidden div. This ensures the popup html will not be displayed on the page. Now to add FancyBox, which ended up less straight-forward as I would have imagined it to be. It seems like FancyBox can only be tied to an anchor tag. So we have to add another layer on top of this.

The HTML:

<a id="inline" href="#popup"></a>

And the Javascript:

$(document).ready(function() {
	$("a#inline").fancybox({
		'hideOnContentClick': true
	});
});
function getData(id)
{
	$.post('/test', "id="+id, function(data){ $('#popup').html(generatePopup(data)); $('a#inline').click();});
}

So the anchor tag will display #popup in FancyBox when clicked. We use jquery to automate that click in the ajax success function.

How do I make a simple accordian menu?

HTML:

<ul>
<li><a href="/">Home</a></li>
<li><a href="#solutionsList" class="heading">Solutions</a>
    <ul>
    	<li><a href="/locate.php">Locate</a></li>
    	<li><a href="/jobs.php">Jobs</a></li>
    	<li><a href="/timesheets.php">Timesheets</a></li>
    </ul>
</li>
<li><a href="/about.php">About</a></li>
<li><a href="#techSupport" class="heading">Technical Support</a>
    <ul>
    	<li><a href="/support.php">Technical Support</a></li>
    	<li><a href="/support.php">Technical Support</a></li>
    	<li><a href="/support.php">Technical Support</a></li>
    </ul>
</li>
<li><a href="/contact.php">Contact</a></li>
</ul>

This is a typical nested list format. The list components that have an unordered child list group inside them need the following.
1) A link with a specified ID
2) A child ul list that has a class equal to the id of the link (from #1)

CSS:

ul{background:#faf7f3; margin:0; padding:0;}
li{display:block;  list-style-type:none; }
li a{ display:block; font-weight:bold; height: 20px; padding: 8px 0 8px 12px;}
li ul{margin: 8px 0 8px 0; padding:0;}
li ul li{display:block; list-style-type:none; font-weight:normal }
li ul li a{ font-weight:normal; padding: 1px 0 1px 12px; }

Just some styling to align the list items and make them look decent.

jQuery:

[script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"][/script]
[script type="text/javascript"]
$(document).ready(function() {
	$('ul#accordion a.heading').click(function() {
		$(this).css('outline','none');
		if($(this).parent().hasClass('current')) {
			$(this).siblings('ul').slideUp('slow',function() {
				$(this).parent().removeClass('current');
			});
		} else {
			$('ul#accordion li.current ul').slideUp('slow',function() {
				$(this).parent().removeClass('current');
			});
			$(this).siblings('ul').slideToggle('slow',function() {
				$(this).parent().toggleClass('current');
			});
		}
		return false;
	});
});
[/script]

Finally the code that makes the toggled list work.

————————–

NOTE: TOGGLE INITIAL SUB-NAVIGATION
You can set one of the toggle contents to be open by checking the URL and use the jquery toggle function on the sublist ID you want visible. The way I did it was to use the ‘indexOf’ function to see if the link contained a certain value. The following code would go after the click function in ‘$(document).ready’:

var loc = window.location.pathname
var pageVar = '#nothing';
if ((loc.indexOf("locate") != -1)||(loc.indexOf("job") != -1)||(loc.indexOf("timesheet") != -1)){
	pageVar = '#solutionsList'}
else if (loc.indexOf("support") != -1){
	pageVar = '#techSupport'}
 
$.fx.off = true;
$(pageVar).slideToggle('800',function() {
	$(pageVar).parent().toggleClass('current');
});
$.fx.off = false;

Adding an exit animation to ::Featured Content Glider

Dynamic Drive has a really useful script called Featured Content Glider.
My only complaint was that the layer kept overlapping the previous one instead of a nice flow by having the previous animate out while the new slide animated in.

So what I did was add some lines to the featuredcontentglider.js

1) add “var startingvar = 0;” after “jQuery.noConflict()
It created a variable that I found useful to know exactly what slide I was on.

2) the if statement following “//Test for toggler not being initialized yet, or user clicks on the currently selected page):” should be replaced with the following if statement:

//Test for toggler not being initialized yet, or user clicks on the currently selected page):
if (config.$togglerdiv.attr('lastselected')==null || parseInt(config.$togglerdiv.attr('lastselected'))!=selected){
	var $selectedlink=config.$toc.eq(selected)
	config.nextslideindex=(selected<config.$contentdivs.length-1)? selected+1 : 0
	config.prevslideindex=(selected==0)? config.$contentdivs.length-1 : selected-1
	config.$next.attr(&#39;loadpage&#39;, config.nextslideindex+"pg") //store slide index to go to when "next" link is clicked on
	config.$prev.attr(&#39;loadpage&#39;, config.prevslideindex+&#39;pg&#39;)
 
	if (startingvar != 0){
		var $previous=config.$contentdivs.eq(config.prevslideindex)
		var startpoint=(config.leftortop=="left")? {left:0} : {top:0} //animate it into view
		$previous.css(config.leftortop, startpoint).css("zIndex", this.csszindex) 
		var endpoint=(config.leftortop=="left")? {left:-config.startpoint} : {top:-config.startpoint} //animate it into view
		$previous.animate(endpoint, config.speed)
	}
	startingvar++;
 
	var startpoint=(isprev=="previous")? -config.startpoint : config.startpoint
	$target.css(config.leftortop, startpoint).css("zIndex", this.csszindex++) //hide content so it&#39;s just out of view before animating it
	var endpoint=(config.leftortop=="left")? {left:0} : {top:0} //animate it into view
	$target.animate(endpoint, config.speed)
 
	config.$toc.removeClass(&#39;selected&#39;)
	$selectedlink.addClass(&#39;selected&#39;)
	config.$togglerdiv.attr(&#39;lastselected&#39;, selected+&#39;pg&#39;)
}

And that is pretty much it. This makes the current slide animate out while the new slide comes in. I think this creates a more friendly rotating feature that is less disruptive to the user experience.

Custom jQuery “lightbox”

One thing I learned this week was how to make my own “lightbox” in jQuery. I’ve always used tools like thickbox or lightbox, but I’ve never actually needed to change some of it’s functionality. Or for that matter, change the look of it other than a quick color swap or two.

The below code is the main HTML of the light box. It’s quite fantastic because anything inside the “modal-container” div can be styled exactly how you need it without the over-extensive code written for other light-boxes:

<div id="overlay"> </div>
<div id="modal-container">Hi I'm a lightbox</div>
<a href="#" class="modeBoxLink">Click me to open modal box</a>

Here’s a little CSS to make it invisible on default and set the overlay and container colors:

#overlay, #modal-container{display:none; } 
#overlay{background:#000; width:100%; height:100%; position:fixed; top:0; left:0;  }
#modal-container{background:#fff; width:820px; height:420px; border:3px #ccc solid; top: 10%; left:50%; margin:0 0 0 -420px; position:fixed;filter:alpha(opacity=100);  opacity:1;}

The below code is the main jQuery commands that makes the lightbox appear and go away:

$(document).ready(function(){
	$('#overlay').click(function() {
		$('#overlay').fadeOut();
		$('#modal-container').fadeOut();
		return false;
	});
 
	$('.modeBoxLink').click(function() {
		$('#overlay').fadeIn(1000);
		$('#modal-container').fadeIn(1000);
		return false;
	});
});

So if you have a link on the main page with class set to “modeBoxLink” it will open up the box you just created! Good for whatever content you need in such a window. ((Don’t forget to include the jQuery library))

All together:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$('#overlay').click(function() {
		$('#overlay').fadeOut();
		$('#modal-container').fadeOut();
		return false;
	});
 
	$('.modeBoxLink').click(function() {
		$('#overlay').fadeIn(1000);
		$('#modal-container').fadeIn(1000);
		return false;
	});
});
</script>
 
<style>
#overlay, #modal-container{display:none; } 
#overlay{background:#000; width:100%; height:100%; position:fixed; top:0; left:0;  }
#modal-container{background:#fff; width:820px; height:420px; border:3px #ccc solid; top: 10%; left:50%; margin:0 0 0 -420px; position:fixed;filter:alpha(opacity=100);  opacity:1;}
</style>
 
<div id="overlay"> </div>
<div id="modal-container">Hi I'm a lightbox</div>
<a href="#" class="modeBoxLink">Click me to open modal box</a>

jQuery Variable Name Practices

On something I was working on this week, this snippet of code created a dilemma in IE8:

frame = "";
 
	if (type == "frame"){
		frame = $("#step_2 [name=frame]:checked").val();
		if (frame =="black/black"){frame = "black";}
		else{frame = "brown";}
	}

The strange thing is that it will actually work in most browsers (firefox, IE9, chrome, etc).   In fact: In IE8, it won’t even get past the first line where the variable is declared. However,  I have found that renaming the variable causing the problems solved the issue quite efficiently.

Looking into why this is the case, browsers end up making global variables for each ID in the window object.  Earlier in my code i indeed had a div with the ID “frame”.  Most current browsers let you overwrite these auto created properties, but earlier versions of IE don’t actually let you.

So, when you create a variable name in jQuery, it’s a good practice to use names that you do not use as IDs in your actual code.  My code solution is below:

frameColor = "";
 
	if (type == "frame"){
		frameColor = $("#step_2 [name=frame]:checked").val();
		if (frameColor =="black/black"){frameColor = "black";}
		else{frameColor = "brown";}
	}

Cookies with jQuery

Being able to set and read cookies asynchronously can be a great feature in many aspects of a web app. If you are looking for such a feature you probably already have jQuery attached to your app. All you need now is the jQuery Cookie plugin. You can pick that up at Here.

Once you have that attached in your files, you can easily start setting and reading cookies.

Set Cookie

$.cookie("cookie_name", "your_value");

Adding Options

$.cookie('cookie_name', 'your_value', { expires: 10, path: '/basepath/for/cookies', domain: 'yourdomain.com', secure: true });

The line above lets you set multiple parameters to the cookie. The above cookie would expire in 10 days and the path will set the area of your site the cookie will work.

If you were to do the same action in strictly javascript you would have to run more detailed code like:

document.cookie = "cookie_name=your_value; expires=16/07/2010 00:00:00; path=/basepath/for/cookies; domain=yourdomain.com";

jQuery is slightly easier to use in this regard but is even better when retrieving the cookie values.

Read Cookie

$.cookie("cookie_name");

Removing a cookie is also easy but they way you do it may not be the first guess a programmer would try without consulting documentation.

Remove Cookie

$.cookie("cookie_name", null);