1

I have a cookie set as yab_uploadmode and it has numeric value ranging from 1-4 and 4 div elements named btn1, btn2, btn3 & btn4,

how can i retrieve the value of cookie and apply style to that particular element without use of any framework.

Thank you very much.

Regards,

Shishant Todi

Daniel
  • 10,864
  • 22
  • 84
  • 115
Shishant
  • 9,256
  • 15
  • 58
  • 79

1 Answers1

1
function getCookie(N){
   if(N=(new RegExp(';\\s*'+N+'=([^;]*)')).exec(';'+document.cookie+';'))
      return N[1]
}

we'll be using the above function to get cookie value.

window.onload=function(){
   var element, cookie = getCookie('yab_uploadmode');
   if(cookie && (element = document.getElementById('btn'+cookie))){
      //element.className = 'newClass'; // you can change the class...
      element.style.color='red'; // ... or a single property
   }
}

if you don't like to use the window.onload property, use the addEvent function instead.

Community
  • 1
  • 1
Rafael
  • 18,349
  • 5
  • 58
  • 67
  • i have added the code to my script header and change element.className to element.style.color= '#333'; i am not getting any errors in firebug but the color is not changing when the page is loaded – Shishant May 14 '09 at 16:21
  • i used onload=getCookie('yab_uploadmode') and also tried wrapping the 2nd part ie var element.....newclass in a function btn and tried onload=btn(); but no success – Shishant May 14 '09 at 16:25
  • tried but no success, i even tried to log the value of element in firebug but the value is not displaying in firebug window.onload=function(){ var element, cookie = getCookie('yab_uploadmode'); if(cookie && (element = document.getElementById('btn'+cookie))){ //element.className = 'newClass'; // you can change the class... element.style.color='#333'; // ... or a single property console.log(element); } } – Shishant May 14 '09 at 16:44
  • Maybe you have other scripts that use window.onload and the code a wrote is being overwritten? When that's true, use the addEvent function that I linked to in my post. Oh, and last question: by saying "4 div elements **named** btn1, btn2, btn3 & btn4," you mean
    or
    ?
    – Rafael May 14 '09 at 16:54
  • my divs has both name and id – Shishant May 14 '09 at 16:56
  • NAME attribute for DIV isn't defined in HTML spec. But that isn't the problem. Have no idea what could cause my code not to work. Tested it on my sample page and everything was working fine. Make sure, there are no other scripts that use window.onload, because this could overwrite my code. Open the Error Console in your browser and check for any reports. If this isn't the case, please prepare a test page. – Rafael May 14 '09 at 17:25