Archive for the ‘Programming Ramble’ Category

jQuery .index()? No thanks… .eq() it is!

Friday, July 17th, 2009

This is just some new jQuery information that just may save you many pots of coffee.

Problem:
Say you have an array of elements, more specifically, and unordered list (ul, li). You would like to make a “next & previous” type function… you need to make this as “pretty as possible.” You can only do this with nifty CSS Classes but it has to be dynamic. For example, at any one time your list can contain 10 elements or even 2! Well, finally after many /faceplants I’ve figured it out!

Solution:
Here is where I save you time & frustration! If you wanted to, you can google away and it will tell you to use the $(<element>).index(<integer>).doWhateverHere(); feature in jQuery.

Well, don’t! For cryin’ out loud, DON’T! It will just cause you to /faceplant and waste many hours of google’n!

The real solution is to use $(<element>).eq(<integer>).<yourWantedActions>

I hope this helps somebody! I may have been wrong in the sense to use .index(), but that is what the basis of programming has always been! Use the “index” to find a certain element or in this case now-a-days using a declared variable for the object

jQuery and Javascript power!

Friday, June 12th, 2009

This is just a quick blog today, but I have been messing around with jQuery/AJAX functionality and what not. This is not something that someone else couldn’t do with a couple of minutes of free time to read.

Here is a snippet of code, using jQuery/Javascript to make an image randomly move about in a container. I’m assuming that you have the plugin livequery added into your jQuery script as well.

HTML

#imgShow {
position: relative;
overflow: hidden;
width: 656px;
height: 255px;
}
#imgShow img {
position: absolute;
top: 0;
left: 0;
}
<div id="imgShow"><img src="/images/test.jpg" alt="" /></div>

Javascript:

function timedGallery() {
$("#imgShow img").livequery(function() {
var maxWidth = 656;
var maxHeight = $("#imgShow").height();
var imgHeight = $(this).height();
var imgWidth = $(this).width();
var maxLeft = maxWidth - imgWidth;
var maxTop = maxHeight - imgHeight;
$(this).animate({ left: Math.round(Math.random() * maxLeft), top: Math.round(Math.random() * maxTop) }, Math.round(Math.random() * 8000 + 3500), timedGallery);
});
}

The run down with the above math is actually pretty simple. Math.random() generates a random number between 0 and 1. Then you can multiply by a number to receive a minimum (0) and max (max[left/top]). Basically: Math.round(Math.random() * 8000 + 3500) means, pick a random number between 0 and 11500. In this case, 0 - 11.5 seconds.

That is all for now, hope all is well!

Side note: In the interest of learning, I created a pretty nifty interface for fun. I tested it on Internet Explorer and it fails horribly. But, if you have FireFox, feel free to check it out: http://www.vipersuite.com