javascript background cookie -
i'm trying write 2 functions set , cookie save user favorite background-color :
function set_background_cookie(){ if ( navigator.cookieenabled ) { favcolor = window.prompt( "insert favorite color please : " , "") ; document.body.style.backgroundcolor = favcolor ; document.cookie = "favoritecolor=" + favcolor + ";" + "expires=sat, 25 apr 2020 12:11:05 gmt" ; } } function get_background_cookie(){ var start , end , color ; var cookiesarray = document.cookie.split(';') ; start = cookiesarray[0].indexof('='); end = start + cookiesarray.length ; color = cookiesarray[0].substring(start + 1 , end ) ; document.body.style.backgroundcolor = color ; }
setting cookie perfect have problem getting problem ??
this whole page :
<!doctype html> <html> <head> <script> function get_background_cookie(){ var start , end , color ; var cookiesarray = document.cookie.split(';') ; start = cookiesarray[0].indexof('='); end = start + cookiesarray.length ; color = cookiesarray[0].substring(start + 1 , end ) ; document.body.style.backgroundcolor = color ; } function set_background_cookie(){ if ( navigator.cookieenabled ) { favcolor = window.prompt( "insert favorite color please : " , "") ; document.body.style.backgroundcolor = favcolor ; document.cookie = "favoritecolor=" + favcolor + ";" + "expires=sat, 25 apr 2020 12:11:05 gmt" ; } } window.onload = function(){ set_background_cookie(); get_background_cookie(); } </script> </head> <body> </body> </html>
try:
end = start + cookiesarray[0].length;
instead of:
end = start + cookiesarray.length ;
you should check cookie exists instead of assuming cookie exists. otherwise javascript errors if user has disabled cookies. should trick:
function get_background_cookie() { if (!document.cookie || !document.cookie.length) return; var cookiesarray = document.cookie.split(';'); var start = cookiesarray[0].indexof('='); var end = start + cookiesarray[0].length; var color = cookiesarray[0].substring(start + 1 , end ); document.body.style.backgroundcolor = color; }
Comments
Post a Comment