How to get Cookie value through Javascript and displaying it in DIV tag:

How to get Cookie value through Javascript and displaying it in DIV tag:

In some cases we may have our webpages with PHP and HTML pages. If we want to display “Welcome {$username} Logout” if user loggedin and “Welcome Login Register” for new users means we can use innerHTML in javascript to achieve our goal.

In above case “{$username}” will be link to user account page. “Register” will link to registration page. “Logout” link to logout page.


function getCookie(Name) {

var search = Name + “=”

if (document.cookie.length > 0) { // if there are any cookies

offset = document.cookie.indexOf(search)

if (offset != -1) { // if cookie exists

offset += search.length

// set index of beginning of value

end = document.cookie.indexOf(”;”, offset)

// set index of end of cookie value

if (end == -1)

end = document.cookie.length

return unescape(document.cookie.substring(offset, end))




function doit()








var sHTML=”Welcome:   <a href=’myaccount.php’>”+uname+’</a>’;

sHTML =sHTML+”   <a href=’logout.php’>Logout</a>”;

loggedin_show.innerHTML = sHTML;


return false;



We can use the above SCRIPT tag within HEAD tag.

getCookie is used to get the cookie names “user_name”. In doit function we can check whether cookie is available. If yes We can assign “Welcome {username} Logout” value to “loggedin_show” DIV. Otherwise we can show “login_show” DIV.

We can call above doit() function as follows.

<body onload=”return doit();”>

login_show div is shown below.

<DIV id=”login_show” style=”display:none”>

Welcome: <a href=”index1.php” mce_href=”index1.php”>Login</a>   <a href=”signup.php” mce_href=”signup.php”>Register</a>


Leave a Reply

You must be logged in to post a comment.

All material @ copyrighted by If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.