Surendra Sharma

Surendra Sharma

Search This Blog

Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Monday, April 13, 2015

How to do versioning of JS and CSS files in ASP.NET

Whenever user access any website - images, JS and CSS are cached by browser. But if JS and CSS are updated on server still client browser refer the old JS and CSS. That’s very bad. It’s always good practice to provide the latest copy of CSS and JS to client browser.

But how to do it in ASP.NET to make sure browser is getting the updated files.

To solve this, we can use query string with JS and CSS.

For CSS, take one literal in <Head> section of aspx page as below

<head runat="server">
<asp:Literal ID="ltStyleCss" runat="server" Text="" ></asp:Literal>
</head>

Write below code

public string CurrentVersion = "";

protected void Page_Load(object sender, EventArgs e)
{
CurrentVersion = DateTime.Today.ToString("MMddyyyy") + "_" + DateTime.Now.Hour.ToString();

ltStyleCss.Text = string.Format("<link href=\"/ css/style.css?ver={0}\" rel=\"stylesheet\" />", CurrentVersion) + System.Environment.NewLine;


Here we are declaring version for each hour of the day.

You can do it for each request by specifyin current datetime, but problem with that approach is that it affects network bandwidth. So per hour solution is better.

It’s very easy to specify it for JS by directly passing the version variable as query string  

<script src="/Presentation/scripts/jquery.js?ver=<%=CurrentVersion%>"></script>

Pretty simple for JS but you can’t achieve the same way for CSS. Let me know if you can do it for CSS as well.


Please leave your comments or share this tip if it’s useful for you.

Sunday, April 12, 2015

How to implement Facebook Tag API script or Facebook Analytic tracking script

Facebook analytic is great way to track your website access by analyzing custom audience source. Facebook called it as Facebook Tag API.

To work with this you need Facebook tracking ID. I represented it as “NNNNN”. In project store it either in web.config or database. Below is script that you need to place it before the end of </body> section of webpage.

    <script>(function () {
    var _fbq = window._fbq || (window._fbq = []);
    if (!_fbq.loaded) {
        var fbds = document.createElement('script');
        fbds.async = true;
        fbds.src = '//connect.facebook.net/en_US/fbds.js';
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(fbds, s);
        _fbq.loaded = true;
    }
    _fbq.push(['addPixelId', 'NNNNN']);
})();
window._fbq = window._fbq || [];
window._fbq.push(['track', 'PixelInitialized', {}]);
    </script>
    <noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?id=NNNNN&amp;ev=PixelInitialized" /></noscript>

This much of information is enough to implement it in any web application like ASP.NET etc. Though programmer don’t like much theoretical reading however you can read more from https://developers.facebook.com/docs/ads-for-websites/tag-api

Please leave your comments or share this script if it’s useful for you.

Saturday, March 7, 2015

How to find any word in string using Jquery

This is simple but very useful method in Jquery to find any word or presence of any substring in any string.

if ($('#txtSearch').val().indexOf('?') < 0)

Here if “?” is present in textbox value then indexIf() method return the position of word in string otherwise return -1 in case of not present.


Please leave your comments or share this tip if it’s useful for you.

Friday, March 6, 2015

How to access the current URL using JavaScript

Many times we need to access current URL of browser using Javascript. Suppose if there is URL like http://www.example.com/guest/index.aspx , now you can access this URL in different pieces as below

alert(window.location.protocol); // display "http:"
alert(window.location.host); // display “www.example.com"
alert(window.location.pathname); // display "guest/example.aspx"

You can get the complete and full URL by concatenating all these different parts

var currentURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;


Please leave your comments or share this tip if it’s useful for you.

Wednesday, August 6, 2014

How to show multiple messages in alert box in JavaScript?

An alert box is used to pop up the information where user has to click “OK”.

alert("This is single line message.");

Generally we are showing single line message in alert box. But do you know how to show multiple message in single alert box?

Trick is to use “\n” after every message to separate one message with other like

alert('-1. Tajmahal in India. \n\n-2. Pyramids in Egypt. \n\n-3. Great wall of China.');

Here I want separation of two lines between each message, so I used “\n\n”.

So finally it should look like this




Please leave your comments or share this tip if it’s useful for you.

Tuesday, August 13, 2013

How to show directions between two locations on Google maps in ASP.NET

        
For displaying directions first identify latitude and longitude of two locations.

To know how to get Latitude and Longitude of any place in Google maps? Please Visit here

Location 1 is act as source point and location 2 is destination point.

I am considering

·         Source Location - 28.67854, 77.23938 - Red Fort, New Delhi, India
·         Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra

UI Design:-

Webpage should display direction map from Red Fort to Tajmahal as below




How to do this in ASP.NET?

Google team already developed API for map and its functionality. These API works with JQuery or Javascript.

ASPX

·         First we need two javascript file. You don’t need to download these file

Map functionality - http://maps.google.com/maps/api/js?sensor=false
JQuery - https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js

·         So its declaration in ASPX file is as below

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>     

·         Create google maps direction service object as

directionsService = new google.maps.DirectionsService();

·         Get the latitude and longitude of source and destination location [Like X,Y co-ordinates in graph in mathematics]

//Source Location - Red Fort, New Delhi, India
sourceLatLng = new google.maps.LatLng(28.67854, 77.23938);

//Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
destinationLatLng = new google.maps.LatLng(27.175114, 78.042154);

·         Set different option of maps like zoom level, alignment of point in map, map type, navigation control as

var mapOptions = {
                    zoom: 15,
                    center: myLatLng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    navigationControl: true
                };

·         Create map object with all specified optins and show in DIV as below

map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

·         Specify the way you want directions on google maps as below

directionsRenderer = new google.maps.DirectionsRenderer({
    'map': map,
    'draggable': false,
    'hideRouteList': true,
    'suppressMarkers': true
});

·         Draw route from source to destination location  in driving mode on maps as

directionsService.route({
    'origin': sourceLatLng,
    'destination': destinationLatLng,
    'travelMode': 'DRIVING'
},
    function(directions, status) {
        directionsRenderer.setDirections(directions);
    }
);

                            
Here is complete ASPX. Just copy and paste below code and bingooooo here you go


ASPX

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Google Map</title>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function() {

            directionsService = new google.maps.DirectionsService();

            //Source Location - Red Fort, New Delhi, India
            sourceLatLng = new google.maps.LatLng(28.67854, 77.23938);

            //Destiation Location - 27.175114, 78.042154 – Taj Mahal, Agra
            destinationLatLng = new google.maps.LatLng(27.175114, 78.042154);

            //set the map options
            var mapOptions = {
                zoom: 15,
                center: destinationLatLng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                navigationControl: true
            };

            //create the map object
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            directionsRenderer = new google.maps.DirectionsRenderer({
                'map': map,
                'draggable': false,
                'hideRouteList': true,
                'suppressMarkers': true
            });

            directionsService.route({
                'origin': sourceLatLng,
                'destination': destinationLatLng,
                'travelMode': 'DRIVING'
            },

                function(directions, status) {
                    directionsRenderer.setDirections(directions);
                }
            );

        });

    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div id="map_canvas" style="width: 900px; height: 600px;">
        </div>
    </form>
</body>
</html>

Please leave your comments or share this tip if it’s useful for you.

Similar articles which you may like

Latitude and longitude, showing image, info popup window on Google maps are necessary base part of Google maps. You can get more info from below articles



Monday, June 24, 2013

How to avoid postback on ENTER key press in textbox or How to block ENTER key press in textbox

$(document).ready(function() {

    // Block ENTER key in textbox
    $('#txtSearch').keypress(function(event) {
        if ((event.keyCode || event.which) == 13) {
            event.preventDefault();
            return false;
        }
    });

})

Thursday, June 20, 2013

Find checkbox in row of each grid using JQuery

if ($(grd.rows[i]).find("input[id*='chkDatabase']:checkbox").attr('checked') == true) {
grd.rows[i].style.display = '';
}
else
{
grd.rows[i].style.display = 'none';

}

Get value from Textbox and convert it into upper or lower case in Jquery

//Get value from textbox and convert in UPPER case
var searchStr = $('#txtSearch').val().toUpperCase();

//Get value from textbox and convert in lower case

var searchStr = $('#txtSearch').val().toLowerCase();