About Tim

  • Website: or email
  • Biography:

Posts by Tim:

 
0

Setting the screen position when visiting previous page with jQuery

On January 18, 2012 in jQuery

The scenario

This problem came while I was working on a client’s website. Take this scenario. I have a listing page (similar to a listing page from www.trademe.co.nz or www.ascent.co.nz ). They have a lot of listings. Each listing has a hyperlink going to a detail page which describes more about each listing.
If you have quite a large page of listings, the user has to scroll down the page to find the listing they want to click on. The problem is, when they click on the link and go to the details page, what happens when the click back and they end up back at the top of the page again? This can be quite annoying. It would be “nice” to get the browser to go back to the previous position on the listing page.

The Approach

We achieve this but attach a click event handler to the specific a tags that we want to record the last clicked position from the user before we redirect to the next page. This means when the user goes back to the previous page they will be taken to the exact position on the page. When the click event happens we always override what was in the cookie so that we don’t end up with several pages and positions. We don’t want a user to go to another page they have been to before and set the scroll position, it should only happen to the previous page.

Here is the code

var COOKIE_NAME = "scroll";
 
$(document).ready(function () {
    // Check to see if the user already has the cookie set to scroll
    var scrollPosition = getCookiePosition(COOKIE_NAME);
    if (scrollPosition.length > 0) {
        // Scroll to the position of the last link clicked
        window.scrollTo(0, parseInt(scrollPosition, 10));
    }
 
    // Attach an overriding click event for each link
    // saveScrollPosition function can be called before the user is redirected.
    $("a.savel").each(function () {
        $(this).click(function () {
            saveScrollPosition($(this));
        });
    });
});
 
// Get the offset (height from top of page and the current page url) of the link element
// and save it in a cookie.
function saveScrollPosition(link) {
    var linkTop = link.offset().top;
    setCookie(COOKIE_NAME, "pos=" + linkTop + "&link=" + escape(window.location.pathname), 1);
}
 
//Trim whitespaces
function trim(str) {
   return str.replace(/^\s+|\s+$/g, '');
}
// Get cookie helper function
function getCookiePosition(name) {
    if (document.cookie.length > 0) {
        //Get the right cookie
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
           
            if (trim(cookies[i].split("=")[0]) == COOKIE_NAME) {
                //Get the position of the & sign
                var pos = cookies[i].indexOf("&");
                if (pos > -1) {
                    //Get value
                    var scrollValue = cookies[i].split("=")[2].substring(0, cookies[i].split("=")[2].indexOf("&"));
                    var link = unescape(trim(cookies[i].split("=")[3]));
                    //if the link is the same as the current page, then assume user wants to go back to the same position
                    if (link == window.location.pathname) return scrollValue;
                }
                return "";
            }
        }
        return "";
    }
    return "";
}
 
//Method to create a new cookie
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}
 
// Set cookie
function setCookie(name, value, expiredays) {
    //Remove all other cookies
    var cookies = document.cookie.split(";");
    for (var i = 0; i < cookies.length; i++) {
        if (trim(cookies[i].split("=")[0]) == COOKIE_NAME) {
            createCookie(trim(cookies[i].split("=")[0]), "", -1);
        }
    }
    //Set the new cookie
    createCookie(name, value, expiredays);
}

Tags: ,

 
0

Magento Fontis Paymate Module Fix for Not Passing Data Issue

On December 28, 2011 in Magento

I upgraded my magento from 1.4.0.1 to 1.6.1 and yes a lot of things broke especially the ability to pay using Paymate. I did some research and found a lot of people having the issue of non data being passed from Magento to Paymate to populate the fields like address, amount etc. Since there has [...]

 
0

When to use TempData in ASP.NET MVC

On December 5, 2011 in MVC

The problem I came across this problem where I had a basic list of items and for each if these items I wanted to add a delete action on my controller. I wanted to add some error checking around the delete action so if someone attempted to modify the URL and enter a incorrect parameter [...]

 
0

Perform ASP.NET Postback using JQuery

On October 27, 2011 in .NET Framework, ASP.NET, jQuery

Came across a situation where I needed to disable the ASP.NET button using JQuery when the user clicks on the button, this is so we stop the user from clicking the button twice while the page is doing a postback. Firstly, add the following JQuery/Javascript code: <script>  function autoSubmit()  {  <%= ClientScript.GetPostBackEventReference(btnSaveChanges, "") %>;  } [...]

 
0

Some useful Extension Methods

On September 6, 2011 in .NET Framework, C#

Back to basics… A couple of useful Extension methods if you are checking if a string is a valid integer or decimal. public static bool IsInteger(this string value) { if (String.IsNullOrEmpty(value)) return false; Int32 tmpNo; return Int32.TryParse(value, out tmpNo); } public static bool IsDecimal(this string value) { if (String.IsNullOrEmpty(value)) return false; Decimal tmpNo; return Decimal.TryParse(value, [...]

 
1

Areas and ASP.NET MVC Routes Tip

On August 28, 2011 in MVC

Lets say that you have several areas define in your ASP.NET MVC solution. You find that when you run your application you get the following error “Multiple types were found that match the controller named ‘Home’.”. This is because ASP.NET MVC finds all the routing definitions (i.e in each area.cs file or the global.asax) and [...]

 
0

OrderBy making null records come last Entity Framework and Linq

On July 28, 2011 in .NET Framework, C#

Ever want to sort your result set but make sure the records with a null sorting column appear last? See the example below var results = (from x in EntityObjectContext.MyTable               select x               into grp               [...]

 
0

Elmah and MVC 3 Error Handling

On July 12, 2011 in ASP.NET, MVC

I came into an issue where I have Elmah configured on a ASP.NET MVC 3 website. I notice that the errors were not getting logged or emailed as per my configuration settings in web.config. I found that MVC3 Error Handling was handling all the errors before Elmah could handle the error and report it correctly. [...]

 
0

Max number of words in textarea using jQuery

On June 7, 2011 in jQuery

Here is a little code snippet to set a maximum of words in a text area element. This could be turned into a jQuery function or refactored to be better reused, but there is a sample just to get you going. $(‘textarea’).keyup(function () {             var wordArray = this.value.split(/[\s\.\?]+/); //Split [...]

 
0

Using UserControl.RenderControl()

On June 7, 2011 in ASP.NET, Visual Basic

Perhaps you want to reuse a usercontrol in a email? or you need to generate the html from a usercontrol for a specific purpose? Firstly, here is the code to render the html from a user control to a string builder object:    Dim sb As New StringBuilder()    Using sw As New StringWriter(sb)   [...]

Copyright © 2008-2012 Codelab Blog All rights reserved.
Desk Mess Mirrored version 1.9.1 theme from BuyNowShop.com.