Inserting 'back to top' link dynamically using jQuery

Introduction

Download


I have seen many articles/blogs etc. on web that has huge information on a single page; some of them already using this technique that I am going to talk.

Okay, for now look at the animated image given below.

Note: Image size is 1.4 MB, please wait to respond.



You can see, whenever I click on 'back to top' URL, page scrolls to top. At very first, you will think that I have inserted something like

<a id="top1"></a>

at the top and at the end of each <p> I have inserted URLs which is like
<a href="#top1">back to top</a> to navigate to top. But you're wrong, this is not my technique. I have inserted these all dynamically, without looking the number of places to insert URL or how huge content do you have at the web page. You can use this feature anytime; all your earlier web page will start functioning. So, what's the magic behind.

Let's look at the jQuery codes

    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('<a href="#top">back to top</a>').insertAfter('div.myPageData  p');
            $('<a id="top"></a>');
        });
    </script>

In above jQuery code, first line has a URL <a href="#top">back to top</a> and it will be inserted after each paragraph <p> inside a <div> that has class "myPageData". And in the second line, inserted a URL and it will take place at the top in the web page body automatically, no need to supply insertAfter() or insertBefore() method for this.

ASPX Code

(Note: Place sufficient text inside each paragraph to see actual navigation, I just have erased and placed dots)

<body>
    <div class="myPageData" style="width: 500px; text-align: justify;">
        <h2>History of Visual Studio</h2>
        <p>
            Visual Studio's history...
        </p>
        <p>
            Those of us that really...
        </p>
        <p>
            It's 1988 and I landed at...
        </p>
        <p>
            So the C product was...
        </p>
        <p>
            Anyway the programming...
        </p>
        <p>
            Debugging used even more...
        </p>
    </div>
</body>

So, the concept is very basic but it is useful.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples