Show div once a day using Javascript

    The following javascript snippet allows you to show a message to the user who visits the page for the first time, and hides the message if he makes subsequent visits to that page on that day. The script involves cookies and thus need to have cookie-enabled in the user browser.

    First lets have a look at the form. The form consists of a single ‘div’ element. The message to be displayed has to be kept inside this div. It can be text or image or any other display content.
<form name="scriptDen">
<div id="myDiv"> Place Your Content Here </div>
</form>
</form>

    Next we have to build the code for creating a cookie. This cookie has to be created when the user visits the page for the first time. The createCookie() function takes name of the cookie, its value and its expiry period(in days) as parameters. Since we are creating a cookie for a day, the expiry period will be one.
function createCookie(name,value,days) {
    // new Date object created
    var date = new Date();
    // adding days to current time
    date.setTime(date.getTime()+(days*24*60*60*1000));
    // converting to standard format
    var expires = date.toGMTString(); 
    // adding cookie name,value and expiry time
    document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}

    Now we need to read the cookies stored in the browser and look whether our cookie is present there or not. The readCookie() function returns true if the cookie stored by us is present and returns false if not.
function readCookie(name) {
    var flag = 0;
    // getting the browser cookie values into an array
    var dcmntCookie = document.cookie.split(';');
    // looping over the array to find our cookie
    for(var i=0;i < dcmntCookie.length;i++) {
        var ck = dcmntCookie[i];
        // loop for removing extra spaces from the beginning of each cookie
        while (ck.charAt(0)==' ') {
            ck = ck.substring(1,ck.length);
        }
        if(ck) {
            // splitting the cookie into its name and value
            cparts = ck.split('=');
            // setting the flag if a cookie with the name specified exists
            if (cparts[0]==name)
               flag=1;
        }              
    }    
    // returning true if cookie exists else returning false 
    if(flag) { 
        return true; 
    } else {
        return false; 
    }   
}

    Now as we have created both the createCookie() and readCookie() function, we have to use them for serving our purpose, that is, to hide/display a div element. This is achieved using the checkCookie() function. It checks for the cookie with a given name specified. If the cookie exists then it hides the div. Else if the cookie is not present, a new cookie is created and added to the browser.
function checkCookie(name) {
    if (readCookie(name)) {
        // hide the div element using css style attribute
        document.getElementById('myDiv').style.display = "none";
        document.getElementById('myDiv').style.visibility = "hidden";
    }
    // create a new cookie if cookie already not present
    else createCookie(name,"cookie 4 the day",1); 
}

This sums up the article. Hope this was helpful. Please do enter your valuable comments and suggestions. You can find the entire code along with html from below.
<html>
<title>show Msg once a day</title>
<head>
<style>
#myDiv {
    border: 1px solid #999;
    width: 350 px;
    height: 100px;
    background: #ccc;
    text-align: center;
}
</style>
<script language="javascript" type="text/javascript">
/** Create a html cookie and set expiry as a day. **/
function createCookie(name,value,days) {
   var date = new Date();
   date.setTime(date.getTime()+(days*24*60*60*1000));
   var expires = date.toGMTString();
   document.cookie = name+"="+value+"; expires="+expires+"; path=/";
}
/** Check if already a cookie has been created. **/
function readCookie(name) {
    var flag = 0;
    var dcmntCookie = document.cookie.split(';');
    for(var i=0;i < dcmntCookie.length;i++) {
        var ck = dcmntCookie[i];
        while (ck.charAt(0)==' ') {
            ck = ck.substring(1,ck.length);
        }
        if(ck) {
            cparts = ck.split('=');
            if (cparts[0] == name) flag=1;
        }              
    }     
    if(flag) { 
        return true; 
    } else {
        return false; 
    }  
}
/** Check if cookie exists else create a new one. **/
function checkCookie(name) {
    if (readCookie(name)) {
        document.getElementById('myDiv').style.display = "none";
        document.getElementById('myDiv').style.visibility = "hidden";
    }
    else createCookie(name,"cookie 4 the day",1); 
}
</script>
</head>
<body onLoad="checkCookie('MyCookie')">
  <form name="scriptDen">
    <center><div id="myDiv"> Place Your Content Here </div></center>
  </form>
</body>
</html>

Passing only non-Empty fields on form submit

Sometimes you have a lot of text-fields and want only those fields to be sent to the server as parameters, which are not left blank (that is which are filled). This helps in decreasing the amount of data being sent to the server.

This is one way of how the above can be done. Lets first start with the basic HTML. The form (say testform) may consists of a number of text fields and a submit button. When the button named “Submit” is clicked, the javascript function “submitFunc()” is called.
<form name="testform">
      <input type="text" name="text1" id="text1"><br />
      <input type="text" name="text2" id="text2"><br />
      <input type="text" name="text3" id="text3"><br />
      <input type="button" onclick="submitFunc();" value="Submit">
<form>
Now about the “submitFunc()” function. This function checks each text field by calling the “loopRemove ()” function.
function submitFunc() {

      loopRemove("text",3);
      document.testform.action = "http://scriptden.blogspot.com";
      document.testform.submit();
}
The “loopRemove()” function loops over the fields, who have a similar name with two parts, one a string (say, ‘text’), suffixed by an integer part in increasing order starting with one (eg. ‘txtField1’,’txtField2’,…).It checks whether the given element’s field value is empty, and if found empty it removes the corresponding element by accessing the element’s parent node.
function loopRemove(startName,count) {
      for(var i=1;i<=count;i++) {
            if(document.getElementById(startName+i).value=="") { 
                  var t = document.getElementById(startName+i);
                  t.parentNode.removeChild(t); 
            }
      } 
}
The action path of the form is specified dynamically and the form is submit using the “form.submit()” function. The form thus submitted (with empty elements removed) will pass only the filled field’s values to the page/location specified in the action path.
document.testform.action = "http://scriptden.blogspot.com";
document.testform.submit();
This sums up the article. Hope this helps.
This post is open for your queries and suggestions.

You can download the entire script here.
Related Posts Plugin for WordPress, Blogger...
 

Copyright © 2012 | ScriptSplash | Powered by Blogger Templates