Search code examples
javascriptcookieshref

cookie checkbox for what href user was chosen


I want to create a 2 button script with a "remember me" checkbox that puts a cookie on the user's browser.
Next time he will enter the site he will be automatically redirected to the link he choose the first time.
I was looking all over for something like this

<div id="container">
    <p>Please Choose Your Preference</p>
    <br/>
    <div class="normal_site"><a href="">Regular Site</a></div>
    <div class="mobile_site"><a href="">Mobile Site</a></div>
</div>

Solution

  • You can try this (jQuery needed). http://jsfiddle.net/infernalmaster/c6cmk/8/

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <div id="conteiner">
        <p>Please Choose Your Preference</p>
        <br>
        <div class="normal_site "><a class="sitelink" href="http://www.regular.com/">Regular Site</a></div>
        <div class="mobile_site"><a class="sitelink" href="http://www.mobile.de/">Mobile Site</a></div>
        <div class="remember"><input id="remember_me" type="checkbox" checked=""> Remember My Selection<div>
    </div>
    
    <script type="text/javascript">
    function validate(){
        $(document).on('click', '.sitelink', function(){ // if user click on link
           var site_pref = $(this).attr('href');         
           if($('#remember_me').is(':checked')){        //if checkbox is checked then 
                                                        //  write link url t cookie
              createCookie('site_pref', site_pref, 30);  // for 30 days
           } else {
              eraseCookie('site_pref');                
           }
           return true;
        });
    
    
        var site_pref = readCookie('site_pref');  //read cookie
        if(site_pref){                             //if cookie present then
            self.location=(site_pref);      //redirect to path form cookie
        }    
    }
    
    validate();
    
    // Taken verbatim from http://www.quirksmode.org/js/cookies.html
    
    function createCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }
    
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    
    function eraseCookie(name) {
        createCookie(name,"",-1);
    }
    </script>