Grow your CSS skills. Land your dream job.

Cookie update problem?

  • # June 18, 2012 at 12:32 pm

    I’m trying to save the current time of the music when the user change pages and play it when the page loads.

    It works fine the first time I save the cookie, then some strange behavior happens.

    Example:
    Start music -> save music time (8242 ms) and change page -> Page loads, gets 8242 from cookie and play song starting at that time -> save music time (10604 ms) and change page -> Page loads, gets 8242 from cookie and play song starting at that time

    I think my code is ok so I’m asking if there’s any problem with uploading cookies in javascript. I’m using Firefox to test it and the important part of the code is below.


    function setCookie(time) {
    var today = new Date(),
    expire = new Date(),
    duration = 5;
    expire.setTime(today.getTime() + 3600000*24*duration);
    document.cookie = "music="+time+";expires="+expire.toGMTString();
    console.log("Set Cookie: " + time);
    }

    function getCookie(check_name) {
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false;

    for ( i = 0; i < a_all_cookies.length; i++ ) {
    a_temp_cookie = a_all_cookies.split( '=' );
    cookie_name = a_temp_cookie[0].replace(/^s+|s+$/g, '');

    if ( cookie_name == check_name ) {
    b_cookie_found = true;
    if ( a_temp_cookie.length > 1 ) {
    cookie_value = unescape( a_temp_cookie[1].replace(/^s+|s+$/g, '') );
    }
    return cookie_value;
    break;
    }
    a_temp_cookie = null;
    cookie_name = '';
    }
    if ( !b_cookie_found ) {
    return null;
    }
    }

    function deleteCookie() {
    document.cookie = 'bushmusic=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    window.onbeforeunload = function (e) {
    if (isPlaying && sm) {
    var time = sound.position;
    if (time != null && !isNaN(time)) {
    setCookie(time);
    } else {
    deleteCookie();
    }
    } else {
    deleteCookie();
    }
    };
Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".