1

I'm building a site using Joomla 3.3.1, and I'd like an alert box to pop up whenever users first visit the site (and not pop up on subsequent page clicks or when refreshing the page). The alert box should say "By visiting this page, you agree to its Terms of Service" with "Terms of Service" being a link to a specific page. And users can click OK. I'm very new to JavaScript, but I tried the code below:

<script>
function TOS(){
alert("By visiting this page, you agree to its Terms of Service.");
}
TOS();
</script>

Unsurprisingly, this made the alert pop up anytime I clicked on anything on the page. I also tried calling the function in the with onload, but I got similar results.

Any guidance or references you can provide would be much appreciated!

BenMorel
  • 34,448
  • 50
  • 182
  • 322

2 Answers2

0

Something like:

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
function TOS(){
    var cookieName = 'hasVisitedBefore';
    var cookie = getCookie(cookieName);
    if (!cookie) {
        alert("By visiting this page, you agree to its Terms of Service.");
        createCookie(cookieName,true,3650);
    }
}
TOS();

I used the createCookie and getCookie functions from this question: How do I create and read a value from cookie?

Here's a working fiddle: http://jsfiddle.net/kvLrt/1/

Community
  • 1
  • 1
Chris HG
  • 1,412
  • 16
  • 20
0

In your index.php file of your template, add the following code under the <body> tag:

<?php
    $alertCookie  = JFactory::getApplication()->input->cookie;
    $value        = $alertCookie->get('alertCookie', '');
    if (!$value){ ?>

    <script>
        function TOS(){
            alert("By visiting this page, you agree to its Terms of Service.");
        }
        TOS();
    </script>
    <?php 
    }
    else{
        $expireCookieUT = echo time() + 10000000;
        $alertCookie->set('alertCookie', '1', $expireCookieUT);
    }
?>
BenMorel
  • 34,448
  • 50
  • 182
  • 322
itoctopus
  • 4,133
  • 4
  • 32
  • 44