Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

27 Apr 2014

How to Automatically Select Content of a HTML element for copy to clipboard

Sometimes you want to let your users to select certain portion of your web content for copying to clipboard, And for this user has to select content manually.
But using below mentioned script anyone can select entire content of a HTML element just by single/double click.

Steps for implementation.
First assign a 'onclick' or 'ondblclick' function with function call (as shown below)to your HTML element.For example,
      <!-- Calling select funtion on double click -->
    <div ondblclick="selectElementContents(this)"> Double click to Select content of this div !! </div>
Now define a JavaScript function named as 'selectElementContents()',
     function selectElementContents(el) {
                    if (window.getSelection && document.createRange) {
                       // IE 9 and non-IE
                       var range = document.createRange();
                       range.selectNodeContents(el);
                       var sel = window.getSelection();
                       sel.removeAllRanges();
                       sel.addRange(range);
                    } else if (document.body.createTextRange) {
                       // IE < 9
                       var textRange = document.body.createTextRange();
                       textRange.moveToElementText(el);
                       textRange.select();
                    }
            }

That's it, Now your user can select entire content just by double clicking inside the element.
Test this code by double clicking above code area.

5 Apr 2014

Creating JavaScript CountDown Timer

CountDown Timers can be useful for many online things like displaying deadline for 'a limited deals' or 'a form submission date'.
In this tutorial we will learn how to develop and implement a simple Pure JavaScript CountDown Timer. Our Final emphasis will be only on JavaScript because display styles can be changed using any custom CSS.
If you are using my css then final result will look something like following image,


So lets get started,

- First of all create a element where you want to display final result.Give each element ID as per required result, for example, 'days','hours','minutes','seconds'
<div class="countDown">
           <span id="days">00</span>     <!-- Remaining Days,id="days"-->
           <span id="hours">00</span>    <!-- Remaining hours ,id="hours"-->
           <span id="minutes">00</span>  <!-- Remaining minutes,id="minutes"-->
           <span id="seconds">00</span>  <!-- Remaining secounds,id="secounds"-->
</div>

- Include .js file,which we will create, having code for countdown,Example, my file is countdown.js, which is in same directory.
<script src="countdown.js"></script> 
- Now call countdown function with end time and callback function name as parameters.[remember, input date format, 'mm/dd/yyyy hh:mm:ss AM/PM']
<script>
           
  countdown('04/05/2014  00:45:00 PM',callback); // Date format ('MM/DD/YYYY  HH:MM:SS TT');
            
  function callback(){
       alert('Time Out'); //Callback Function Definition

  };
</script>
now we will create our countdown function,following below mentioned key concepts,
i. get current time
ii. subtract from End time [input value]
iii. convert remaining time [milliseconds] in days,hours,minutes,seconds [or add years,months, if you want]
iv. repeat step (iii) every second till remaining time is greater then or equals to zero.

//JavaScript Function for CountDown Timer, In countdown.js file 

function countdown(endT,callback) {
        var days,hours,minutes,sec,timer;
        
        end = new Date(endT);
        
        end = end.getTime(); //Get initial Date in Milliseconds,
        if (isNaN(end)) {
           alert('@ countdown.js @  "Invalid Date", valid format- mm/dd/yyyy hh:mm:ss TT ');
           return;
        }
        
        timer = setInterval(calculate,1000);//Timer to calculate remaining time

        function calculate(){
         var current = new Date();
         var remaining = parseInt((end - current.getTime())/1000);//remaining seconds, 
          
            if (remaining <= 0){
                clearInterval(timer);
                days=0;
                hours=0;
                minutes=0;
                sec=0;
                display(days,hours,minutes,sec);
                if (typeof callback === 'function' ) {
                    callback();
                }
                
            }else{
                
                days = parseInt(remaining/86400);
                remaining = (remaining%86400);
                hours = parseInt(remaining/3600);
                remaining = (remaining%3600);
                minutes = parseInt(remaining/60);
                remaining = (remaining%60);
                sec = parseInt(remaining);
                display(days,hours,minutes,sec);
                
                
            }
        }

        //Function For displaying Results in HTML page with specific ID's 
        function display(days,hours,minutes,sec) {
            var dl = days.toString().length;
            if (dl == "1") {
                sl = 2;
            }else{
                if (isNaN(dl)) {
                    sl = 3;
                }
                sl = dl;
            }
            document.getElementById("days").innerHTML = ("00"+days).slice(-sl);
            document.getElementById("hours").innerHTML = ("0"+hours).slice(-2);
            document.getElementById("minutes").innerHTML = ("0"+minutes).slice(-2);
            document.getElementById("seconds").innerHTML = ("0"+sec).slice(-2);
        }
     
    }
Finally our CountDown timer is ready and result will look something like following texts,
00 01 04 41
Add some css to make it look pretty, Below is css code to decorate above result text, use this or create your own.
/* CSS for CountDown Timer,Notice I have added labels (days,hours,minutes,seconds) using :After pseudo class, you can add these in HTML itself*/ 
            .countDown{
                display: inline-block;
                margin: auto;
            }
           
            .countDown span{
                display: block;
                background: #000;
                color: #fff;
                height: 54px;
                float: left;
                margin-right: 5px;
                padding: 8px;
                border-radius: 5px;
                font-size: 45px;
                line-height:normal;
                text-align: center;
                box-shadow: 2px 2px 8px #747474;
                background-image: url("http://goo.gl/7IC8sK");/*If You want image background*/
                background-size: contain;                     /*If You want image background*/
                background-repeat: repeat-x;                  /*If You want image background*/
            }
            
            #days:after,#hours:after,#minutes:after,#seconds:after{
                
                font-size: 14px;
                line-height:normal;
                display: block;
                width: inherit;
                margin-top: 10px;
                color: #5C5757;
                text-align: center;
            }
            #days:after{
                content: "Days";
            }
            #minutes:after{
                content: "Minutes";
            }
            #hours:after{
                content: "Hours";
            }
            #seconds:after{
                content: "Seconds";
            }
working Demo,
Time Remaining for :

00 00 00 00