E-com DevBlog Spider-ball-vacuum

14Apr/102

Using jQuery to Make a Smart Search

Recently I've been forced to develop a relationship with jQuery (something I had no interest in while I was working with team awesome). I have to admit it has been quite pleasant and my tolerance has grown into a very strong liking of the library (so I'm a little slow). This proved very useful when I was asked to make a search field do more than just search for an ID. I decided NOT to fowl up our nice sleek looking header with a clunky drop down box, instead I turned to jQuery to make the search bar intuitive...observe.

?View Code JAVASCRIPT
$("#searchForm").submit(function() {
	//the regular expressions in this function are not meant for validation as much as determining which value to search by.
	var submitted_appid = $(".search input[name=AppID]").val();
 
	if(/^[\d]+$/.test(submitted_appid) == true) {
		//do nothing since the input is already properly named
	} else if(/^[\d-]+$/.test(submitted_appid) == true) {
		//change name of input to SSN
		$(".search input[name=AppID]").attr("name","SSN");
	} else if(/^[A-Za-z]+$/.test(submitted_appid) == true) {
		//change name of input to LastName
		$(".search input[name=AppID]").attr("name","LastName");
	} else {
		//no match, alert the rep and return false
		alert("invalid search value:\nfor SSN please use numbers and at least one dash '-'\n for LastName use only letters\n for AppID use only numbers")
		return false;
	}
	//there was a match add an action and submit the form.
	$(this).attr("action",'search.php');
	$(this).submit();
});

The HTML

<div class="search">
    <form id="searchForm" name="searchForm" method="post" action="">
	<input type="text" name="AppID" value="Search..." />
    </form>
</div>

Then your search app would do something like the following

if(isset($_POST['AppID']) {
     //enter sql code here
} else if(isset($_POST['SSN']) {
    //enter sql code here
} else if(isset($_POST['LastName']) {
   //enter sql code here
}

Basically the jQuery decides what to search on based on the characters in the input field, if the wrong mix of characters is present then we fire off an alert message notifying the irresponsible party and correcting their ignorant ways.

Print This Post Print This Post
28Apr/092

Pop-ups, the interweb, and you

The problem*: You have a page with a pop-up, and when you click a link on it, it needs to change the page that spawned it.

I searched everywhere and every result listing let me down. Site after site was bitter disappointment, I searched for 'pop-up close child window redirect parent', then 'pop up change parent', and 'pop up child link change parent window'. I did find some useful code like the 'onunload' event (we'll cover that another time ;) ). I finally stumbled onto the solution by mashing up a few different solutions that were posted for javascript events and the mysterious 'window' method built into the base js library*².

The solution (#1): This solution is for those who want to keep the pop-up open, or just want parent only manipulation (yeah, you can always manipulate the child (pop-up), but solution 2 is soooo much easier for that).

First, let's build a method to handle pop-ups.

?View Code JAVASCRIPT
function popWindow(url, myWidth, myHeight, myScrollbars, myTop, myLeft, myMenubar, myResize) {
	window.name = "main"; /* setting this is the key to letting you manipulate the parent window */
	window.open(url, "","width="+myWidth+",height="+myHeight+",scrollbars="+myScrollbars+",top="+myTop+",left="+myLeft+",menubar="+myMenubar+",resizable="+myResize+",bgcolor=#ffffff");
}

Note that we used "window.name" and set it to "main".  This allows me to reference the parent window from any child windows (pop-ups).  Now that we've done that, in our pop-up window we just need to make the link have a target of "main".  Like so:

<a href="http://fakedoman.com/newpage.html" target="main">Change the parent window!</a>

Now this comes together on your parent page, you click a link that uses the popWindow function that creates the pop-up that can now reference the parent by the name "main".

The solution (#2): This is the show, the heat, the expletive, the new hotness, and the fresh burnination. Ok, fine, it's old code that's been around forever that everyone on the internet forgot about (or at least didn't blog, write, post, etc).

In your pop up window, build a method like this in your script section (or included js file).

?View Code JAVASCRIPT
function openParent(webAddress){
	opener.location.href=webAddress;
	window.close();
};

Wow... 2 lines (4 if you count the open and closer of the function), simple, easy. Why has no one told anyone else about this*³ ? Now the only thing left is to call that function in an "onclick" event in your a-tag.

<a href="javascript:void(null);" onclick="javascript:openParent('http://fakedomain.com/newpage.html');"/>

Yes, I pointed the href to "javascript:void(null);", the onclick event will overwrite the original href call anyway, so this is how you build the link to keep the code valid to W3c standards.

And that, my friends, is how you code a pop-up window that will change the parent window with a link from the pop-up window.

 


 

* Yes I heard all of you grumblers in the back saying 'change the target in the a-tag to "_top" and that'll solve your problem. And you know what? yeah, in 1998 that would have worked. However these days our pop-ups are javascript based, and not so frames/iframe-y.

*² This statement could very well be false... in fact it's made up, I'm not sure if it's built in, I really can't back that up, yeah, total b.s. and yet the code works in IE6, IE7, IE8, Opera 9.63, Safari 3, Firefox 2, Firefox 3, and Chrome... so that kinda seems "built-in", or at least understood and interpreted correctly by most browsers.

*³ It could be that pop-ups in legitimate sites really aren't all that common, and generally the people who use them on their sites are spammers/malware/spyware vendors and should be dragged out in the street and beaten while having their selling slogans chanted and shouted at them (isn't that a pleasant picture you just painted in your head? your welcome).

Print This Post Print This Post
17Mar/091

Object Doesn’t Support this property or method

Just a quick post to spread more love about IE. Occasionally I run into an error on IE (who doesn't) that boggles my mind, like reading toaster directions when they throw in the verticle concept. Anyhow this particular one I've seen before but not sure I've ever known what causes it. I tried to click a submit button that when clicked is supposed to run some validation on the form. Works great in FF2 and 3 but not so much in IE, instead I get this error "Object Doesn't Support this property or method" then it attempts to give me a line and character number to look at but it's way off (as you may have guessed). So I googled this baby and the first post I read on it was the helpful-est. so I'll link to it for you pleasure but also give you the quick and dirty (too late). basically this happens if one of your js functions has the same name as one of your HTML ID's or it can also happen if a JS variable has the same name as a Form Element name which was what was happening in my case. Easy fix just change the name of one or the other and your all set.

Here is the post

Print This Post Print This Post
Tagged as: , , 1 Comment
23Feb/090

Quickpost: nyroModal – another jQuery plug-in to keep an eye on

Over the last week or three Internal Apps had a problem where they wanted to display a page, but have a window appear with new contract terms visible. They also needed a scroll bar, buttons to accept/decline, print, and close the pop-up. They also needed a little twist, if the user declined the new contract, or closed the pop-window, the page should send them back to the log in page.

I thought about the problems, and I was thinking recommending to them FancyBox (our old standby for modal windows), but I had just read on another site about nyroModal. I recommended that they try it out (since it's jQuery you have all those great callback functions - that would cover the page redirection etc. - and those oh-so-tasty visual effects that would provide them with exactly what they had envisioned), and within a day they had a perfect set up. So if you find that you need a modal box (for whatever reason), I suggest you give nyroModal a try. We ourselves won't be dumping FancyBox anytime soon, but it is nice to have another option.

Print This Post Print This Post
7Jan/090

IE6 and form submit fixery

Yesterday presented a problem I was unfamiliar with, and while ie6 continues to be the bain of all web developers existance, I finally was able to emerge triumphant, with the head of the demon tucked nicely under my arm... for now. The problem of course is trying to submit a form through javascript with ie6.

After poking around the large interweb I stumbled on another site that had run into the same problem. a slightly more indepth description of the problem is that you have a form, but rather than use a submit button, you have an image wrapped in an a-tag that you have assigned a click-event too that submits the form (or sends it to some js validation, and then submits the form). This is all fine-and-dandy with any 'modern' web browser, but for some reason that only m$ can tell us, when ie6 follows the a-tag, it gets lost without ever submitting the form, it doesn't even attempt to load the page.

Some people have reported that adding an empty anchor to your a-tag fixes the problem (you know, a simple >a href='#'<), but we like code that validates, so we usually insert ye olde 'javascript:void(null);' into our a-tags when we handle them with onclicks, or jQuerify them.

The solution that we ended up using was to use a setTimeout(); around the form submit in the js. For some reason, this allows ie6 to remember what it was supposed to do and get it done. I like to think of it as a virtual kick in the teeth to the browser. Anyway, here is some sample code to help you visualize the problem and solution.

Here is our form, (yes, it has a smattering of JSTL in it ;) , you can ignore that if it bothers you)

?View Code HTML4STRICT
<div class="review-form-input">
	<a href="javascript:document.reviewForm.submit();">
		<img src="<c:out value="${jspStoreImgDir}" />en_US/submit.gif" alt="Submit" />
	</a>
</div>

And here is our sample javascript code BEFORE being fixed (note the jQuery goodness, that I can't use enough of)

?View Code JAVASCRIPT
$(document).ready(function(){
	$(".submit a").click(function(){
		$("#reportForm").submit();
	});
});

Note that the above code works fine in Opera 9+, Safari 3+, Firefox 3+ (and most-likey but untested in Firefox 2+), and yes even the black-sheep of the browser family ie7 can render and run this code just fine.

Here is the fixed javascript...

?View Code JAVASCRIPT
$(document).ready(function(){
	$(".submit a").click(function(){
		setTimeout('$("#reportForm").submit();', 50);
	});
});

Yep, that's it, a very subtle change, just inserting the setTimeout() method fixes the ie6 stupidity.

Print This Post Print This Post
19Dec/080

DD_belatedPngFix – A new solution to an aging problem

This has already been reported on several tutorial/dev sites, but I thought I'd put in a word or two about it.  DD_belatedPngFix is a fantastic little piece of work created by Drew Diller.  Drew has taken a unique approach to fixing the many issues that plauge ie6 and png files.  Instead of the standard alphaimageloader he uses just a touch of VML to tweak the images into appearing correctly, this allows for png files to be used as backgrounds and eliminates the annoying problem of trying to click on an image/div/whatever that was in another div with a background set to a png.

I started to set NordicTrack up with this script, but found that it's not quite perfected with objects that have absolute positioning (if anything on the page is a png that is above where your positioning the absolute element, they will build themselves as blocks, then knock each other out of the way), or with png sprites (your roll-over image is zoomed in a little so it appears 'cut-off').  Drew is regularly updating his script (which is awesome) so hopefully he'll have these issues fixed soon. --UPDATE (03/19/2009)! So after doing a bit more research (and a few updates to the js from Drew) this may no longer be an issue. If you remove the "position: relative, z-index: 1" from your png elements (or containers) the dd_belated png fix will work like a champ! NordicTrack has been converted and has been running dd_belated for just over a month now (so go and firebug the code ;) and see how I made it work) with no crazy formatting errors!

So in short, if you need a png fix that is simple, easy, and you don't want to throw "position: relative; z-index: 1" on all your elements that have a png in them (or as a background).  This is definetly something you'll want to check out.

Here's that link again, in case you missed it -> http://www.dillerdesign.com/experiment/DD_belatedPNG/ .

Print This Post Print This Post
6Nov/080

Brillar Resurrected and perfected.

Remember long ago when Sid, and Remo and I (and Bryce but he probably doesn't remember this cuz he is in infernal apps) started and there was this javascript function called Brillar? Well nobody seemed to understand the brillar function but we had to use it over and over again for image swapping, and I was just getting to the point that I almost knew how to use it without cheating. But then Phil killed it with jQuery and we have all partied since.

WELL THE PARTY IS OVER! Recently I've needed to do a rollover effect on some Input images and wasn't sure exactly how to do it with jQuery, come to think of it I am not sure how to do much with jQuery, so I turned back the clock and resurrected the Brillar function. only now it's hotter, better, more dynamic smaller and yes hotter. In fact it's so hot Phil and I renamed it to "BrillarCaliente".

Now instead of passing Two or three (can't remember for sure but it was a lot) parameters in your onmouseover/onmouseout calls, you only need to pass one.

?View Code HTML4STRICT
onmouseover="javascript:BrillarCaliente(this);" onmouseout="javascript:BrillarCaliente(this);"

The rest is in the Javascript function, thus making it easier to change what images/path's are to be used.

?View Code JAVASCRIPT
<script type="text/javascript">
function BrillarCaliente(image){
	var hostpath = '<c:out value="${standardUrlPrefix}${jspStoreImgDir}" escapeXml="true" />';
	var id = image.id;
	var source = document.getElementById(id).src;
	if(source == hostpath+'sml-addcart.gif'){
		document.getElementById(id).src = hostpath+'sml-addcart-on.gif';
	} else {
		document.getElementById(id).src = hostpath+'sml-addcart.gif';
	}
}
</script>

Ok so maybe it's not perfect but it's whole lot better than it was. The only thing I don't love is that I had to set up the "id" var in order to set up the "source" var, if there is a way around it I'd love to know.

Now for those of you who are reformists and love jQuery, I'm quite confident that this is doable in jQ with about 3 lines of code. Either way is better than what we used to do.

Alternativley if you wanted to make this more dynamic you could do the following:

?View Code HTML4STRICT
onmouseover="javascript:BrillarCaliente(this, 'newimage.jpg');" onmouseout="javascript:BrillarCaliente(this, 'oldimage.jpg');"
?View Code JAVASCRIPT
<script type="text/javascript">
function BrillarCaliente(image, swapImage){
	var hostpath = '<c:out value="${standardUrlPrefix}${jspStoreImgDir}" escapeXml="true" />';
	var id = image.id;
	var source = document.getElementById(id).src;
	if(source == hostpath+'sml-addcart.gif'){
		document.getElementById(id).src = hostpath+swapImage;
	} else {
		document.getElementById(id).src = hostpath+swapImage;
	}
}
</script>

note the extra param passed through to the function, I haven't actually tested it but it should work.

Print This Post Print This Post
29Oct/080

JavaScript Conditional Compilations

I don't think it's any secret amongst Team Awesome or it's affiliates that I hate IE (in fact I'm pretty sure we all do) and more specifically I hate IE6, so everytime we code a new site I'm all for not supporting IE6, my motto...."punish the IE6 losers, I mean users, I mean losers" but I'm far from getting my way. Even though it appeared I might with NT2.2, ultimatley I was defeated. And it's kinda sad to because if we got away from that more than half of those who are still on IE6 would upgrade because they would realize they are behind. Anyhow in an effort to find a polite way to explain to those poor suckers that there are better more advanced browsers out there I found a way to use JavaScript to detect the javascript version of the users browser and if that version matches IE6 display a single alert box to inform them of their folley. Sure there are other ways but I found this one kinda interesting.

?View Code JAVASCRIPT
<script type="text/javascript">
/*@cc_on
	/*@if(@_jscript_version < 5.7)
		alert('We have detected that you are using an older browser, for a better user experience please upgrade your browser to IE7 or something totally better altogether like Firefox or Safari, or even Chrome or the PS3 browser for crying out loud.');
	@end
@*/
</script>

for more information on Conditional Compilations go Here

For more informatoin on the PS3 Browser go Here

Print This Post Print This Post
12Jun/081

Aptana: an IDE for JS/AJAX developers

One of the things that I really like when I develop is a good IDE.  Now I don't usually use all the extra bells and whistles but I like auto-complete, error checking, and a solid testing engine/server.

When I first jumped on the java train, I used a community version of SunOne Studio.  It was nice, it only crashed when you didn't want it too, and was the right price (for educational purposes).  Later  when I took more java classes I used JBuilder, for a about a week.  I'm not saying JBuilder is bad, it's just not as free as Eclipse (my current favorite IDE for all my java needs).

Anyway to shorten the story, I use eclipse (or a variant like EasyEclipse) for my java and php development, but I had not found an IDE that supported prototype and jQuery (and by support I mean the previously mentioned features, you know, auto-complete, error checking, etc).  That all changed when I somehow stumbled onto aptana studio.

Aptana is a fantastic IDE that is based on Eclipse, but features a built-in rendering engine/server, support for all the popular javascript libs (prototype, jQuery, mooTools, mochikit, Dojo...) and is brimming with scripts, snippets, and helper libraries.  They have even developed an interesting technology called "jaxer" (which stands for ajax-server).  I haven't played with Jaxer yet, but it sounds like it can do some fascinating things.  There are also plug-ins for iPhone development, AIR support, and PHP development.

What I mostly use Aptana for is testing new web 2.0 pages.  For example, on one of our sites we redesigned the press release page.  Development on that site is done in WebSphere 5.6.1, which means I have to dig out a VM and do my work in there... which is lag-tastic (especially the test server).  With Aptana, I can test everything cleanly up front and see what I'm going to get (with a quick page mock-up) before I attempt to code the whole thing in the VM.  If you're bored, give it a try, it's a fairly hefty download, but it's worth playing with it.

Aptana comes in two flavors, Community and Pro.  There is a comparison chart on the aptana studio download page.

Print This Post Print This Post
4Jun/080

A slightly closer look at JSMin

A month or three ago I did a post on different JS compression utilities.  At that time I had decided that the YUI compressor was the best.

"In my opinion YUI is the best, you can choose several different compression levels and it works very well compressing prototype, so well in fact that we got it to shrink down an extra 10k than what had been done with  ShrinkSafe.  Also the YUICompressor is semi-intelligent with whitespace, it checks for ascii characters before and after a piece of whitespace to know if it should remove it."

After learning a bit more, I haven't completely changed my mind, but I thought that I would mention JSMin a bit more. The main reason for this second look is that when combined with gzip (or deflate), JSMin really is a wonderful solution to compressing your javascript files (and the solution recommended by the jQuery team).

Speaking of jQuery, you can use JSMin to shrink the jquery.js down from 95k to 53k. Then you can use gzip on your server and it will crunch down to about 15k! I haven't tried using gzip on a yui compressed file, but it may have the same problems that a PACKED js file has. Meaning gzip either won't work on it, or your functions will "esplode".

You can grab JSMin here (at the time of this post, the link to download the file is at the bottom of the page).

Print This Post Print This Post