JayDee
JayDee

Reputation: 1643

How to update cookie value without page refresh using jQuery?

I'm currently using jQuery Cookies plugin, and depending on which side of the page a viewer clicks, a cookie is applied:

<div id="leftClick">Click Me</div>
<div id="rightClick">Click Me</div>

The problem is once the cookie is stored, it doesn't update without a refresh. So if the viewer clicked on the right element, but before refreshing the page, then followed the left element it would still report right_ despite the cookie having been overwritten with _left, as the page hasn't refreshed. Is there a way of reading the cookie realtime without a page refresh?

<script type="text/javascript">
    var readCookie = $.cookie('whichSide');
    $(document).ready(function() {
       $('#leftClick').click(function(){
        $.cookie('whichSide', 'left_');
      }); 
    $('#rightClick').click(function(){
        $.cookie('whichSide', 'right_');
      });
    $('#login').click(function(){
        _gaq.push(['_trackEvent', 'viewerChose', readCookie+'side']);
    });   
  });  
​</script>  

Upvotes: 2

Views: 10016

Answers (3)

jfriend00
jfriend00

Reputation: 707278

Remove this from your code as you are caching the value of the cookie yourself.

var readCookie = $.cookie('whichSide');

Change your code to this where you get a fresh copy of the cookie value every time you need it in the $("#login").click() handler rather than refer to a previously saved value:

<script type="text/javascript">
    $(document).ready(function() {
       $('#leftClick').click(function(){
        $.cookie('whichSide', 'left_');
      }); 
    $('#rightClick').click(function(){
        $.cookie('whichSide', 'right_');
      });
    $('#login').click(function(){
        _gaq.push(['_trackEvent', 'viewerChose', $.cookie('whichSide')+'side']);
    });   
  });  
​</script>

Upvotes: 2

Cody
Cody

Reputation: 3764

You're reading the readCookie value only once, and then using that value in the .click function. Try reading it in the click event so you'll be using the newest value:

$('#login').click(function(){
    var readCookie = $.cookie('whichSide');
    _gaq.push(['_trackEvent', 'viewerChose', readCookie+'side']);
}); 

Upvotes: 3

mekwall
mekwall

Reputation: 28974

This is because you are storing the value of your cookie in the readCookie variable. This variable will not be automatically updated when you update your cookie which is why you are getting the old value when referring to it.

You probably want something like this:

$('#login').click(function(){
    _gaq.push(['_trackEvent', 'viewerChose', $.cookie('whichSide')+'side']);
});

Upvotes: 5

Related Questions