Archive for category Javascript

Grouped pagination links function in JavaScript

I just created a JavaScript port of an awesome bit of pagination code I first used years and years ago while working in Classic ASP, originally written by Dave Child who I was working with at the time. The original can be found on this site here.

It’s an awesome script when you have 100′s of pages of data (which probably suggests you need to implement some good filtering and search features to save your poor users..) and presents the links like so..

« Prev 1 2 3 … 7 [8] 9 … 208 209 210 Next »

function BuildGroupedPagination(current_page, total_pages, base_url, seperator) 
{ 
	var url = base_url; 
	var strPages = ""; 
	var intMaxPages = 0;
	var intMinPages = 0;
	var intPaginI = 0;

    if (typeof(seperator) == 'undefined')
    {
        seperator = " ";
    }

	if (total_pages > 10) 
	{ 
		if (total_pages > 3) 
		{ 
			intMaxPages = 3;
		}
		else 
		{
			intMaxPages = total_pages;
		} 

		for (intPaginI = 1; intPaginI <= intMaxPages; intPaginI++) 
		{

			if (intPaginI == current_page) 
			{ 
				strPages += "<strong>[" + intPaginI + "]</strong>";
			}
			else 
			{
				strPages += "<a href=\"" + url + intPaginI + "\">" + intPaginI + "</a>";
			} 

			if (intPaginI < intMaxPages) 
			{ 
				strPages += seperator;
			} 
		} 

		if (total_pages > 3) 
		{ 
			if ((current_page > 1) && (current_page < total_pages)) 
			{ 
				if (current_page > 5) 
				{ 
					strPages += " ... ";
				}
				else 
				{
					strPages += seperator;
				} 

				if (current_page > 4) 
				{ 
					intMinPages = current_page;
				}
				else 
				{
					intMinPages = 5;
				} 

				if (current_page < total_pages - 4) 
				{ 
					intMaxPages = current_page;
				}
				else  
				{
					intMaxPages = total_pages - 4;
				} 

				for (intPaginI = intMinPages - 1 ; intPaginI <= intMaxPages + 1; intPaginI++) 
				{
					if (intPaginI == current_page) 
					{ 
						strPages += "<strong>[" + intPaginI + "]</strong>";
					}
					else 
					{
						strPages += "<a href=\"" + url + intPaginI + "\">" + intPaginI + "</a>";
					}

					if (intPaginI < intMaxPages + 1) 
					{ 
						strPages += seperator;
					}
				}

				if (current_page < total_pages - 4) 
				{ 
					strPages += " ... ";
				}
				else 
				{
					strPages += seperator;
				} 
			}
			else 
			{
				strPages += " ... ";
			} 

			for (intPaginI = total_pages - 2; intPaginI <= total_pages; intPaginI++) {
				if (intPaginI == current_page) { 
					strPages += "<strong>[" + intPaginI + "]</strong>";
				}
				else {
					strPages += "<a href=\"" + url + intPaginI + "\">" + intPaginI + "</a>";
				} 

				if (intPaginI < total_pages) { 
					strPages += seperator;
				} 
			} 
		}
	}
	else 
	{
		for (intPaginI = 1; intPaginI <= total_pages; intPaginI++) 
		{
			if (intPaginI == current_page) 
			{ 
				strPages += "<strong>" + intPaginI + "</strong>"; 
			}
			else 
			{
				strPages += "<a href=\"" + url + intPaginI + "\">" + intPaginI + "</a>";
			} 

			if (intPaginI < total_pages) 
			{ 
				strPages += seperator;
			}
		}
	}
	return strPages;
}

6 Comments

jqZoomage jQuery component

I’ve built a simple jQuery plugin for use on a website I’m building and am in the process of submitting it to the jQuery plugins website. It’s a simple zoom panel, allowing your users to mouse over portions of your small image, to see a close up view. Ideal for use on product details page or similar.

Screenshot

Installation

Just add a reference to the script at the bottom of your page (where all your js should be anyway!)- as shown in the demo, this is a basic example;

$(window).ready(function() {
	$("#dinky-img").zoomage({
		zoomedImageContainer: "#big-img",
		zoomedImageUrl: "big-image.gif",
		stayActiveOnMouseOut: false,
		zoomedImageStartsCentered: true
	});
});

There are a couple of styles which are required for the view finder, and the mask which goes over the image (allowing you to customise the look)- add these rules to your style sheet somewhere;

#zoomage-view-finder { border: 1px solid #fff; }
.zoomage-view-finder-surround { background-color:#fff; opacity:0.7; }

As a general point, it’s best to run the script in a $(window).load() rather than the standard $(document).load(), as this ensures that all the images are loaded before the script begins, otherwise the script runs and grabs the width() and height() of the image to work out ratios, but these get returned as 0′s! More info on this can be found on the stack overflow issue about this

Configuration

zoomedImageContainer * Required *
Default Value : “#zoom-image-container”
This is the jQuery selector for the div which will act as the close up view for your image.

zoomedImageUrl * Required *
Default Value : “”
This is the URL of the zoomed image file. I generally use images 3 times larger than the original, however there isn’t a limit. The scale ratio is calculated on load.

stayActiveOnMouseOut
Default Value : false
If this is set to true, the view finder will continue to show in it’s last position even when the mouse pointer is moved off of the image. If false, the view finder will disappear on mouse out.

zoomedImageStartsCentered
Default Value : true
Indicates that, on load, the zoomed image view shows the center of the image.

centerOnMouseOut
Default Value : true
If true, on mouse out, the zoomed view will return to the center of the zoomed image.

Live Demo

You can check out a real life working version of it here!

Tested across all the major modern browsers (IE9/ FF4/ Chrome10)- give me a shout if you spot an issue.

Download

Current Version 1.2 – 2011-09-10
Unminified Development Version
Minified Production Version

Licence

This plugin is available for use under the MIT licence. For more info see http://codeblog.shawson.co.uk/storage/jquery.zoomage/licence.txt

jQuery Plugin Site Link

The official jQuery Plugin catalogue link for this plugin is http://plugins.jquery.com/project/jqZoomage

11 Comments

New Adobe HTML5 Animation tool “Edge”- free tech preview

A real nail in the coffin for Flash, as it’s own parents (Adobe) release a free tech demo version of Edge- A new editor that lets you make flash style animations– without Flash! Instead the animations are scripted using standards html5, JavaScript and CSS3. Having been hand coding stuff like this over the past year (for 8week game and the like) I’m interested to see what kind of code this tool actually spits out! Check it out herel; http://t.co/I46QFYm

3 Comments

Adding minification and obfuscation of your Javascript and CSS to your ASP.net build process using Yahoo YUI Compressor

I’ve just finished integrating Yahoo’s YUI Compressor into the MSBuild process for a new web probject I’m working on, and I thought I would document the process as there doesn;t seem to be a start to finish guide about anywhere.

To start with, let me just explain the structure I use for new Solutions;

C:\_Dev\MyNewWebsite\
C:\_Dev\MyNewWebsite\Artwork\
C:\_Dev\MyNewWebsite\BuildTools\
C:\_Dev\MyNewWebsite\Docs\
C:\_Dev\MyNewWebsite\Source\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.sln
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Controls\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Images\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Scripts\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Services\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\Styles\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Web\MyNewWebsiteWeb.csproj
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Entities\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Entities\MyNewWebsiteEntities.csproj
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Interfaces\
C:\_Dev\MyNewWebsite\Source\MyNewWebsite.Interfaces\MyNewWebsiteInterfaces.csproj
C:\_Dev\MyNewWebsite\ThirdParty\

Firstly, download the dot net port of the YUI compressor from codeplex. I then extracted this into a new folder in the BuildTools folder. (there should be 2 dll files and one txt licence file.)

I then created a new MSBuild file called build-minify.xml, in the MyNewWebsite.Web project folder. That file looks like this;

<?xml version="1.0" encoding="utf-8"?>
<!-- http://yuicompressor.codeplex.com/wikipage?title=Sample%20MSBuild.xml%20File&amp;amp;amp;amp;amp;ProjectName=yuicompressor -->
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask
         TaskName="CompressorTask"
         AssemblyFile="..\..\BuildTools\Yahoo.Yui.Compressor-v1.5.0.0\Yahoo.Yui.Compressor.dll" />

  <ItemGroup>
    <CssFiles Include="$(SourceLocation)Styles\Fonts.css"/>
    <CssFiles Include="$(SourceLocation)Styles\Site.css"/>

    <CssIE Include="$(SourceLocation)Styles\IE.css"/>
    <CssIE6 Include="$(SourceLocation)Styles\IE6.css"/>

    <JsAll Include="$(SourceLocation)Scripts\jquery-1.6.1.min.js" />
    <JsAll Include="$(SourceLocation)Scripts\jquery-ui-1.8.14.custom.min.js" />
    <JsAll Include="$(SourceLocation)Scripts\json2.js" />
    <JsAll Include="$(SourceLocation)Scripts\jqModal-r14.js" />
    <JsAll Include="$(SourceLocation)Scripts\jquery.tipsy.js" />
    <JsAll Include="$(SourceLocation)Scripts\jquery.scrollTo-1.4.2.min.js" />
    <JsAll Include="$(SourceLocation)Scripts\jquery.localscroll-1.2.7.min.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-alert.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-validation.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-rollovers.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-custom-accordion.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-vehicle-lookup.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-sandbox.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-finance-calculator.js" />
    <JsAll Include="$(SourceLocation)Scripts\chinook-apply-now.js" />
    
  </ItemGroup>

  <Target Name="Minimize">
    <CompressorTask
              CssFiles="@(CssFiles)"
              DeleteCssFiles="false"
              CssOutputFile="Styles/Site.rel.css"
              CssCompressionType="YuiStockCompression"
              DisableOptimizations="Nope"
              EncodingType="Default"
              LineBreakPosition="-1"
              LoggingType="ALittleBit"
              ThreadCulture="en-gb"
              IsEvalIgnored="false"
            />

    <CompressorTask
              CssFiles="@(CssIE)"
              DeleteCssFiles="false"
              CssOutputFile="Styles/IE.rel.css"
              CssCompressionType="YuiStockCompression"
              DisableOptimizations="Nope"
              EncodingType="Default"
              LineBreakPosition="-1"
              LoggingType="ALittleBit"
              ThreadCulture="en-gb"
              IsEvalIgnored="false"
            />

    <CompressorTask
              CssFiles="@(CssIE6)"
              DeleteCssFiles="false"
              CssOutputFile="Styles/IE6.rel.css"
              CssCompressionType="YuiStockCompression"
              DisableOptimizations="Nope"
              EncodingType="Default"
              LineBreakPosition="-1"
              LoggingType="ALittleBit"
              ThreadCulture="en-gb"
              IsEvalIgnored="false"
            />
    
    <CompressorTask
      JavaScriptFiles="@(JsAll)"
      ObfuscateJavaScript="true"
      PreserveAllSemicolons="true"
      DisableOptimizations="false"
      EncodingType="Default"
      DeleteJavaScriptFiles="false"
      LineBreakPosition="-1"
      JavaScriptOutputFile="Scripts/chinook.rel.js"
      LoggingType="ALittleBit"
      ThreadCulture="en-gb"
      IsEvalIgnored="false"
		/>
  </Target>
</Project>

You can create whatever ItemGroups you’d like- then just create a compressor task for each. For a rundown of the settings, check out the link in the comment at the top of the XML there. In the above file I had decided to compress all of my Javascript into a single file called chinook.rel.js, and my fonts and site css file rolled into one file, keeping the ie6 css separate, but still minifying it down.

The next step is to add it to the normal build. I opened the solution in Visual Studio, right clicked my web project and selected properties. Go to “Build Events” and add the following post-build event;

$(MSBuildBinPath)\msbuild.exe  $(ProjectDir)build-minify.xml /target:Minimize

Now you can test it out by building your project. The new minified files are dumped out, in my case to the Scripts folder. Now that the files are there, I need a way of telling my release version of the website to use these instead of the raw, human-readable versions; but I still want to continue using the human-readable versions for development.

To achieve this I use pre-processor directives. These are most commonly seen in the c# code behind files, but can also be used in the aspx files. I added the following lines at the bottom of my master page;

    <% #if (!DEBUG) %>
    <script src="Scripts/chinook.rel.js" type="text/javascript"></script>
    <% #else %>
    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>    
    <script src="Scripts/jqModal-r14.js" type="text/javascript"></script>
    <script src="Scripts/chinook-alert.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>
    <script src="Scripts/chinook-vehicle-lookup.js" type="text/javascript"></script>
    <script src="Scripts/chinook-sandbox.js" type="text/javascript"></script>
    <script src="Scripts/chinook-finance-calculator.js" type="text/javascript"></script>
    <script src="Scripts/jquery.scrollTo-1.4.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.localscroll-1.2.7.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tipsy.js" type="text/javascript"></script>
    <script src="Scripts/json2.js" type="text/javascript"></script>
    <script src="Scripts/chinook-validation.js" type="text/javascript"></script>
    <script src="Scripts/chinook-apply-now.js" type="text/javascript"></script>
    <script src="Scripts/chinook-rollovers.js" type="text/javascript"></script>
    <script type="text/javascript" src="Scripts/chinook-custom-accordion.js"></script>
    <% #endif %>

So if the project is NOT running in debug mode, I import my full chinook.rel.js include which has everything already included, otherwise I manually include all the human readable, separate files.

And that’s pretty much it. Make sure you thoroughly retest your site with your combined java script file, as sometimes minification can cause issues with some code.

2 Comments

Front end web developer coding standards

Well put together, and generally good advice about the finer details of javascript (closures, truthy values) for someone starting out.

http://taitems.github.com/Front-End-Development-Guidelines/

No Comments

Adding Javascript Unit Testing/ Compression to your MSBuild

A couple of resources- I shall add to this post as I look into this myself.  I basically want to add steps to my project file, so msbuild will run javascript tests (qUnit) and perform minification/ combines all the js source files.

No Comments

Javascript profiling in IE7…

…cannot be done with the built in dev tools, as I reminded myself today.  I guess my memory painted a fonder picture of the first version of the IE debugger than it deserved.  I’ve been using the IE8 debugger a lot of late as I’m working on a very JS heavy UI targeted primarily at IE users, which has some firebug-esque features, like break points/ profiling etc and I foolishly assumed such things were always there, because a web debugger without these tools wouldn’t be much use..

Anyway turns out all is not lost- after wading through a bunch of rubbish solutions I eventually found  an awesome profiler (for free, of course!) which works with IE 6, 7 & 8!  Check it out- “DynaTrace AJAX Edition

1 Comment

Javascript development on Cloud9… unless you’re on Windows :(

Update 2011.03.03
@rikarends from the Cloud9 team was nice enough to chat to me on Skype about my windows woes and I’m reliably informed that the Windows chunk of Cloud9 still needs a little polishing and will be up to scratch in a future release; you can follow them on twitter for news (@Cloud9IDE) – in the mean time older branches from GitHub should run fine (v0.2.0)- in the mean time you can always run their most up to date version from their hosted service at http://c9.io


Very excited to try out a new HTML5 IDE for Javascript launched this week called Cloud9- you can sign up for an account and hosting, in much the same way as GitHub, however you can also download the project to run locally via NodeJS.

I did have some trouble with this though- I ran git command to download the project to my computer, no probs, then ran the run batch file (I’m on Win7 x64) and this ran about half way then died with this little beauty;

Failed to recurse into submodule path 'support/ace'

:| All looked a bit bleak for a moment- did a bit of Googling and found other people had had this issue- dug through the launch script and found the command that gets fired on first time launch which seems to get a bunch of support packages from Git- this seems to be what failed- I CD’ed into the cloud9 folder and manually re-ran that get

git submodule update --init --recursive

And it seems second time’s the charm- everything finished downloading– that’s not to say I got it running!  Also found a problem in the batch file which starts it up in bin/cloud9-win32.bat – the use of EQ on the if conditions broke the script so I adjusted line 9 to;

IF NOT %ERRORLEVEL%==0 goto exit

and line 18 to;

IF %ERRORLEVEL%==0 goto exit

Now it manages to make it through the script only to say

E:\cloud9\cloud9>bin\cloud9-win32.bat
------ Starting Cloud9 server ------
"Something failed unfortunately, please try a clean clone"
Press any key to continue . . .

Digging into the script once more the command which gets fired to launch it is;

start support\node-builds\win32\node bin/cloud9.js -a "cmd /c start"

So I launched this without the “start” at the command line and the underlying error is;

E:\cloud9\cloud9>support\node-builds\win32\node bin/cloud9.js -a "cmd /c start"
2 Mar 21:05:17 - socket.io ready - accepting connections

                           Ajax.org Cloud9 IDE
                              version 0.2.0
Project root is:
Trying to start your browser in: http://localhost:undefined

So port undefined is obviously no use; I mod the batch script again to specify a port- in bin\cloud9-win32.bat line 16 I change to;

start support\node-builds\win32\node bin/cloud9.js -p 3000 -a "cmd /c start"

This sets the default port to 3000 and relaunching the batch file actually now fires it up- but still it doesn’t work. The browser lauches and I can see bits of the top menu from the UI- however in the accompanying console window I get spammed with errors such as;

Error: Command failed: execvp(): No such file or directory

    at ChildProcess.exithandler (child_process:80:15)
    at ChildProcess.emit (events:27:15)
    at Stream. (child_process:148:12)
    at Stream.emit (events:27:15)
    at Array.0 (net:1004:12)
    at EventEmitter._tickCallback (node.js:55:22)
    at node.js:772:9

I give up! If any one gets futher, please drop me a comment!

10 Comments

Work Starts on my WebGL Game!

Caught up in all the excitement of WebGL becoming more mainstream, I’m building another javascript game. My first offering to the browser based game community was Manic Spaceman, a straight platform game based on ManicMiner which was a little rough around the edges, but boshed out on the quick for the 8weekgame competition.

This time round I intend to go full 3d, taking advantage of WebGL, and make a desert strike style game. I considered starting from scratch, as I did with Manic Spaceman, and writing my own engine to power it all, however given that I’ve next to no 3d experience I thought I would reduce the scope a little and use an engine that’s already out there. After about a week of research I’ve settled for Three.js – I say “settled”, but it’s actually shaping up to be a pretty awesome engine. There’s are a few decent engines out there, all obviously in their infancy, but having reviewed the feature set and looked at the demo’s and read around other developers experiences,  Three feels like the best choice. The other’s I considered were;

The Short List

Other contenders

I only considered open source offerings and looked for engines which

  • were still being actively developed (!)
  • seemed performant with high poly counts
  • handle shadows/ reflections
  • exposed access to GLSL
  • UV Mapping support
  • be relatively stable.

It was surprising how many engines had broken demo’s on their site, which never bodes well, but on the whole, they are all good offerings with almost all of them fulfilling my requirements.

While building my game, I shall be working through some OpenGL tutorials I found- a port of the well known NeHe OpenGL tutorial set, on LearningWebGL.com, which should put me in good stead to build my next game totally from scratch.

I shall post updates as I have something to show.  So far I’ve written a HeightMap generator which works from a greyscale bitmap to build terrains, and I’m currently working on getting the model to follow the landscape; I’ve a long road ahead!

3 Comments

Random Band Generator!

Just a quick post to mention that I’ve uploaded the Random Band Generator- just a bit of fun I boshed together built for a mate… check it out here.

No Comments