Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Adding "Show Less" "Show More" feature using jQuery

Requirement:
  1. You have a list of dynamically generated p tags on your page and the length of the contents varies abnormally.
  2. You want to normalize the length of the content of the p tags to a threshold value of 350 characters.
  3. For all the p tags having length greater than 350, the remaining content should be hidden and there should be a link saying ‘… more’.
  4. There should be a tolerance limit of 20 characters i.e. if the p tags having length equal to 370 (350 + 20) characters, it should be left as it is.
Method body:
  function SetMoreLess(para, thrLength, tolerance, moreText, lessText) {
            var alltext = $(para).html().trim();

            if (alltext.length + tolerance < thrLength) {
                return;
            }
            else {
                var firstHalf = alltext.substring(0, thrLength);
                var secondHalf = alltext.substring(thrLength, alltext.length);

                var firstHalfSpan = '' + firstHalf + '';
                var secondHalfSpan = '' + secondHalf + '';
                var moreTextA = '' + moreText + '';
                var lessTextA = '' + lessText + '';

                var newHtml = firstHalfSpan + moreTextA + secondHalfSpan + lessTextA;

                $(para).html(newHtml);
            }
        }
Step 1: add class “summary” to the p tag(s) Step 2: Iterate over all p tags and call the above function SetMoreLess like this.
  SetMoreLess($(this).find("p.summary"), 350, 20, " ... more", " ... less");
Step 3: bind ShowMore and ShowLess click events ( in page_load or $(document).ready())
   
            $("a.moreText").click(function () {
                $(this).hide();
                var pTag = $(this).parents("p.summary");

                $(pTag).find("a.lessText").show();
                $(pTag).find("span.secondHalf").show();
            });

            $("a.lessText").click(function () {
                $(this).hide();
                var pTag = $(this).parents("p.summary");

                $(pTag).find("a.moreText").show();
                $(pTag).find("span.secondHalf").hide();
            });

Step 4: add css styles used in the code
      
        a.moreText
        {
            color: blue;
            cursor: pointer;
            padding-left: 5px;
            padding-right: 10px;
        }
        
        a.lessText
        {
            cursor: pointer;
            color: blue;
            display: none;
            padding-left: 5px;
            padding-right: 10px;
        }
        
        span.secondHalf
        {
            display: none;
        }

Download example here.

My new repository at GitHub - Custom AJAX Extenders

Check out my new repository jQExtenders. It includes some custom ASP .Net AJAX Extenders built to make use of some commonly used javascript functionality and jQuery plugins. Currently it has SelectAllCheckBox and ListComplete extenders and I plan to add more in the near future.

https://github.com/danish160/jQExtenders .

How to find parent container of an element using jQuery

For finding the parent of an element, there are built-in functions in jQuery like .parent() or .parents() which return the immediate parent element or all the parents in the hierarchy respectively for an element.

This method would work in some cases but mostly you would like to find a particular parent of an element, not just the immediate one nor the list of all parents in the hierarchy.

The correct way of doing this is to compose you query using parent’s selector with child(known element)’s selector as a filter applied on it. For example you have HTML like this.

 <style type="text/css">
.divlevel1{border: 2px solid gray; background-color: aqua; width: 500px; height: 600px;}
.divlevel2{border: 2px solid gray; background-color: fuchsia; width: 400px; height: 300px;}
.divlevel3{border: 2px solid gray; background-color: teal; width: 200px; height: 100px;}
</style>
<script type="text/javascript">
$(document).ready(function () {
$("#myButton").click(function () {

});
});
</script>
<div class="divLevel1">
<div class="divLevel2">
<div class="divLevel3">
<input id="myButton" type="button" value="Change Color" />
</div>
</div>
<div class="divLevel2">
<div>
</div>
</div>
</div>

on the click of button i want to change css of the button’s parent which is two levels up in the hierarchy. one way of doing this is,

$(this).parent().parent().css("border", "3px solid red");

this method will be very unreliable as you go up in the hierarchy. it is not a good approach to add chains to .parent().parent() .

consider this code,

$("div.divLevel2:has(input[id=" + $(this).attr("id") + "])").css("border", "3px solid red");

here i have selected div with class divlevel2 but only the one which has the buttons being clicked in of its children. so instead of going from child to parent, we went from parent to child.

final code will look like this.

$(document).ready(function () {
$("#myButton").click(function () {
$("div.divLevel2:has(input[id=" + $(this).attr("id") + "])").css("border", "3px solid red");
});
});

Convert code into controls, make life easier

Code re-usability is an important aspect of Object oriented programming but mostly it is taken as inheritance and polymorphism only. When you come across a unique requirement, you think over it, get to solution and implement it. This particular solution is very specific to that very problem. However there is always a chance that you could implement the same solution for the same problem in a way that it could also be used for some other case but with a little bit of tweaking or even by addition of values to some parameters. This is what computer science is all about generalization.

Let’s consider an example. You are a C# developer and you are writing an application, let’s say an HR Management System. The system has a lot of data validation, emailing facility, document uploading and even a virus scan. You want your system to catch any exceptions, do any exception handling work and sideways make a log of these exceptions. You wrote a class which would take an exception object as an input and write it to a text file on the machine as well as email it to a certain support email address.

A few days later when you are working on another application, you need similar exception logging. What is ideal here is to go the previous project. Copy the code of exception logging class and create another project and add the same class into it. Compile it. Add a reference to its output in the previous (HR Management in this case) project. Now you will replace the references of the older exception logging class with this newly added external class. Using a re-factoring tool like ReSharper is a good idea here. Sideways you will make necessary changes in the external class to make it generic.

Now you will return to that new project again and use the same exception logging class reference here as well. Life is a bit easier now.

ASP .net GridView BoundField DataFormatString attribute not being applied

If you are trying to set a format specifier in DataFormatString attribute of ASP .Net's GridView Column (Bound Field) thorigh the designer, you might face a problem. The attribute value is not applied although you see that it has been set correctly through the designer.


Some people suggest that if you set the HTMLEncode property to TRUE, then it will do the job, but the actual solution that worked for me is to use the source instead of designer and set the correct DataFormat Specifier.

How to retrieve the next value from identity column of a table

Syntax:
Select Ident_Current('table name here') +1

Example:
Select Ident_Current('Inquiry') +1

Dodging the Modal Popup Extender

I wanted the ASP .Net AJAX Toolkit's Modal Popup Extender to appear at some condition, not at the click of a button, that checks that condition.

I accomplished this extender to some dummy button and made that button hide. Whereas called PopupObj.Show() method on the desired condition. But there is still a problem that the popup appear without PostBack only on the click event of the button with whcih it was made. You cannot set TargetControlID of the popupExtender object to any other button on runtime and achieve that functionality.

Instead you can use Update panel for this pupose.

How to Access DataTable from a SqlDataSource Control

First convert source of a SQLDataSource into a DataView,
DataView dv1 =  (DataView)SqlDataSource2.Select(new DataSourceSelectArguments());

then Cast it as DataTable using ToTable() method of DataSet,
DataTable dtSpecTable1 = (DataTable)dv1.ToTable();

Now 'dtSpecTable1' contains your desired DataTable. If u know how to convert such
a dataTable into a named DataTable, please share here in comments.

ASP .Net DataList Strange Errors

I am using ASP .Net's DataLIst control for Data binding in one of my projects. Everything was working fine. In the item command event, I was using value of text from a label which is databound to a primary key (datatype float). But it was rounding off the float value to 13 decimal places when storing as Text of Label. So I could not use it anymore as a primary key for the row which is represented by the current item.

Then I switched to the dataKeys collection of DataList and it was working fine because DataKeys also storss the whole set of primary key values of the current dataset/datatable. But suddenly it started storing DBNull instead of the primary key value in some specific kinds of records, not all of them. I tried it amny times but nothing worked. Naturally I had to switch towards the Text property of Label for those specific Items. 

LinkWithin

Related Posts with Thumbnails