Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Saturday, August 8, 2015

Start /Stop Asp Timer Control using javascript

In this article i will demonstrate how to control the asp.net Timer Control using javascript.
When we add a timer control to a web page it will add the following script to the page.
<script type="text/javascript" > //<![CDATA[ Sys.Application.add_init(function() { $create(Sys.UI._Timer, {"enabled":true,"interval":5000,"uniqueID":"Timer1"}, null, null, $get("Timer1")); }); //]]> </script>
Now in aspx page i was refreshing page after fixed time using timer control.But the problem was that when i was performing certain actions the page would refresh and this behaviour is not as expected.While performing any operations page should not refresh.To solve this issue i stoped the timer control using javascript and when the task is completed again i start the timer control.In my example i will open a modal popup from gridview and it closes after page refresh .The various methods available for timer control at clientside using javascript are:-
For stop timer control tick event - timer._stopTimer();
For start timer control tick event - timer._startTimer();
For change interval of timer - timer.set_interval(5000);
For checking whether timer is enabled - timer.get_enabled();
For enabling and disabling timer -timer.setenabled(true); true for enabling and false for disabling.
Below is the code i used to solve this issue.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="StopTimer.aspx.cs" Inherits="StopTimer" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script> function showpopup() { var timer = $find('<%= Timer1.ClientID %>'); timer._stopTimer(); console.log("Timer stopped"); $('#myModal').modal('show'); } $(document).ready(function () { $(".custom-close").on('click', function () { var timer1 = $find('<%= Timer1.ClientID %>'); var value = $('#<%=DropDownList1.ClientID %>').val(); timer1.set_interval(parseInt(value)); timer1._startTimer(); $('#myModal').modal('hide'); } ) }); </script> </head> <body> <form id="form1" runat="server"> <div> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="custom-close" >&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <p>Some text in the modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" >Close</button> </div> </div> </div> </div> <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> <asp:ListItem Text="Refresh Every 5 sec" Value="5000" Selected="True"></asp:ListItem> <asp:ListItem Text="Refresh Every 1 Min" Value="60000" ></asp:ListItem> <asp:ListItem Text="Refresh Every 2 Min" Value="120000"></asp:ListItem> <asp:ListItem Text="Refresh Every 3 Min" Value="180000"></asp:ListItem> </asp:DropDownList> <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick"></asp:Timer> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"> <Columns> <asp:TemplateField HeaderText="Price"> <ItemTemplate> <asp:Label ID="Label1" runat="server" CssClass="btn " onclick="showpopup();" Text='<% #Eval("Price") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Datetransaction"> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<% #Eval("Datetransaction") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Productcode"> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<% #Eval("Productcode") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class StopTimer : System.Web.UI.Page { string connStr = ConfigurationManager.ConnectionStrings["Test"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { Timer1.Interval = Convert.ToInt32(DropDownList1.SelectedValue); if (!IsPostBack) grdibind(); } protected void grdibind() { SqlConnection con = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select top 1000 * from Sales"; cmd.Connection = con; con.Open(); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind(); con.Close(); } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Timer1.Interval = Convert.ToInt32(DropDownList1.SelectedValue); } protected void Timer1_Tick(object sender, EventArgs e) { grdibind(); } } On Clicking any cell of the Price column a popup will open using showpopup() thereby stopping timer control using _stopTimer().When close of Modal popup again i call _startTimer().

Tuesday, February 18, 2014

Enable copy & right -click in a webpage that is copy protected.

Many a times when we visit a webpage and try to copy some content from the page ,we are unable to copy that content. There are two possibilities that you are unable to copy.
1)Webpage has disabled the right click of the webpage.
2)The webpage has disabled select of the webpage.
Now here is the solution to these scripts .

For enabling right click just copy the below script and paste it in browser url of the same page

javascript:void(document.oncontextmenu=null)

For enabling copy just copy the below script and paste in browser url of same page


javascript:void(document.onselectstart=true)

Friday, March 22, 2013

Linkify all URLs that appear in a paticular div

Many times we come accross situation that our webpage contains urls but we
forget to give links to it at the time of uploading.
Now here is a simple javascript code that we can give at body load and it will search all urls in page and give them links.

<script>function linkify(text){
    if (text) {
        text = text.replace(
   /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '">' + url + '</a>';
            }
        );
    }
        document.getElementById("hi").innerHTML = text;
}</script>

<body onload="linkify(document.getElementById('hi').innerHTML)"> 

Note: here "hi" is the div that contains text to be converted into links.

Monday, March 18, 2013

My simple tool tip on mouse over and mouse click

Create a tooltip.js file.

function ToolTip(id,isAnimated,aniSpeed)
{ var isInit = -1;
  var frm,divWidth,divHeight;
  var xincr=10,yincr=10;
  var animateToolTip =false;
  var html;
  
  function Init(id)
  {
   frm = document.getElementById(id);
   if(frm==null) return;
   
   if((frm.style.width=="" || frm.style.height==""))
   {alert("Both width and height must be set");
   return;}
   
   divWidth = parseInt(frm.style.width);
   divHeight= parseInt(frm.style.height);
   if(frm.style.overflow!="hidden")frm.style.overflow="hidden";
   if(frm.style.display!="none")frm.style.display="none";
   if(frm.style.position!="absolute")frm.style.position="absolute";
   
   if(isAnimated && aniSpeed>0)
   {xincr = parseInt(divWidth/aniSpeed);
    yincr = parseInt(divHeight/aniSpeed);
    animateToolTip = true;
    }
        
   isInit++; 
   
  }
  
    
  this.Show =  function(e,srcpath)
  {
    if(isInit<0) return;
    
    var newPosx,newPosy,height,width;
    if(typeof( document.documentElement.clientWidth ) == 'number' ){
    width = document.body.clientWidth;
    height = document.body.clientHeight;}
    else
    {
    width = parseInt(window.innerWidth);
    height = parseInt(window.innerHeight);
    
    }
    var curPosx = (e.x)?parseInt(e.x):parseInt(e.clientX);
    var curPosy = (e.y)?parseInt(e.y):parseInt(e.clientY);
    
    frm.src=srcpath;
    
    if((curPosx+divWidth+10)< width)
    newPosx= curPosx+10;
    else
    newPosx = curPosx-divWidth;

    if((curPosy+divHeight)< height)
    newPosy= curPosy;
    else
    newPosy = curPosy-divHeight-10;

   if(window.pageYOffset)
   { newPosy= newPosy+ window.pageYOffset;
     newPosx = newPosx + window.pageXOffset;}
   else
   { newPosy= newPosy+ document.body.scrollTop;
     newPosx = newPosx + document.body.scrollLeft;}

    frm.style.display='block';
    //debugger;
    //alert(document.body.scrollTop);
    frm.style.top= newPosy + "px";
    frm.style.left= newPosx+ "px";

    frm.focus();
    if(animateToolTip){
    frm.style.height= "0px";
    frm.style.width= "0px";
    ToolTip.animate(frm.id,divHeight,divWidth);}
      
    
    }

    

   this.Hide= function(e)
    {frm.style.display='none';
    if(!animateToolTip)return;
    frm.style.height= "0px";
    frm.style.width= "0px";}
    
    
    ToolTip.animate = function(a,iHeight,iWidth)
  { a = document.getElementById(a);
         
   var i = parseInt(a.style.width)+xincr ;
   var j = parseInt(a.style.height)+yincr;  
   
   if(i <= iWidth)
   {a.style.width = i+"px";}
   else
   {a.style.width = iWidth+"px";}
   
   if(j <= iHeight)
   {a.style.height = j+"px";}
   else
   {a.style.height = iHeight+"px";}
   
   if(!((i > iWidth) && (j > iHeight)))      
   setTimeout( "ToolTip.animate('"+a.id+"',"+iHeight+","+iWidth+")",1);
    }
    
   Init(id);
}

Now add these functions to thee page where you want to call tooltip

<script language="javascript">
        var t1;
var timeout;
        function showDetails(e, empid) {
            if (t1) t1.Show(e, "<br><br>Loading...");
document.getElementById("a1").style.display = "none";

//these lines are used when we are having multiple tootlips in page.
            document.getElementById("a2").style.display = "none";
            var url = 'defectstooltip.aspx?def_id=' + empid;
            document.getElementById("a").src = url;
        }

        function hideTooltip(e) {
            if (t1) t1.Hide(e);
        }

</script>

add events to links onmouseover ="showDetails(e, empid);" and onmouseout="hideTooltip(e)"

Note we can also call this tooltip on click event just make small change in function

function showDetails1(e, empid) {
            setTimeout(function () {
               
                if (t2) t2.Show(e, "<br><br>Loading...");
                document.getElementById("a").style.display = "none";
                document.getElementById("a2").style.display = "none";
                var url = 'commentbox.aspx?def_id=' + empid;
                document.getElementById("a1").src = url;
            }, 1000);
        }



Monday, September 10, 2012

Numbers Only in textbox



<SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
 <asp:TextBox ID="txtname" runat="server" Width="241px" BorderColor="#CCCCCC"
                                    BorderStyle="Solid" BorderWidth="1px" CssClass="txtradius"
onkeypress="return isNumberKey(event)"></asp:TextBox>


 

Sunday, September 9, 2012

Alphabets validation in Asp.net with javascript



<script type="text/javascript">

       function validate(key)
       {
           
           var keycode = (key.which) ? key.which : key.keyCode;
           var phn = document.getElementById('text');
           //comparing pressed keycodes
           if ((keycode < 65 || keycode > 90) && (keycode < 97 || keycode > 122))
            {
               return false;
           }
           
         
       }
</script>


<asp:TextBox ID="text" runat="server" onkeypress="return validate(event);"></asp:TextBox>

Please enter ID as your textbox id in function  above
And this function in head section

Tuesday, June 12, 2012

Disable right click on your page

<script language=javascript>
var message="Function Not Allowed";
function clickIE4()
{
         if (event.button==2)
        { alert(message); return false; }

}
 function clickNS4(e)
{
           if (document.layers||document.getElementById&&!document.all)
              { 

                     if (e.which==2||e.which==3)
                  { alert(message); return false; 

                   }
               }
}
 if (document.layers)
{ document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4; }
 else
if (document.all&&!document.getElementById){

document.onmousedown=clickIE4; }
 document.oncontextmenu=new Function("alert(message);return false")
</script>