Davis
Davis

Reputation: 3017

How to set a cookie in jquery using toggle()

Looking for a cookie to be set when the user clicks on the link it'll open the div then the user can refresh the page and see the div is still open.

=======HTML=======

<a class="show-settings" href="#"></a>

========jQuery=======

$(function () {
//Toggle Settings
var s = $("a.show-settings"); 

//On click to toggle settings
s.click(function () {
    $("#s4-ribbonrow, #s4-titlerow").toggle();
});
//Add/Remove text
s.toggle(function () {
    //$(this).text("Hide Settings");
}, function () {
    //$(this).text("Show Settings");
});

Upvotes: 4

Views: 4783

Answers (3)

Hupperware
Hupperware

Reputation: 979

Something like this using jquery-cookies and the callback functionality from toggle

$(document).ready(function() {
 SetView();

 $('.show-settings').click(function() {
  $('#s4-ribbonrow, #s4-titlerow').toggle(0, function(){$.cookie('show-settings', $("#s4-ribbonrow:visible")});
 });

 function SetView() {
  if ($.cookie('loginScreen') == 'true')
   $('#s4-ribbonrow, #s4-titlerow').show();
 }
}

Upvotes: 0

shaunsantacruz
shaunsantacruz

Reputation: 8930

You'll need jQuery cookie for this to work.

$(function() {
    var $s = $("a.show-settings");

    //On click to toggle settings
    $s.click(function() {
        var text = $(this).text();
        $("#s4-ribbonrow, #s4-titlerow").toggle();
        if(text === 'Show Settings') {
            $s.text('Hide Settings');
            $.cookie('is-hidden', null); // remove cookie
        }else {
            $s.text('Show Settings');
            $.cookie('is-hidden', 'hidden'); // set cookie
            }   
        return false;
    });
    if($.cookie('is-hidden')) { // If cookie exists
        $("#s4-ribbonrow, #s4-titlerow").hide();
        $s.text('Show Settings');
    }
});

HTML (assumes settings are shown by default)

<a class="show-settings" href="#">Hide Settings</a>

Upvotes: 0

roobeedeedada
roobeedeedada

Reputation: 521

I've used this jQuery plugin before quite reliably for almost the exact same purpose. It's very light-weight and the documentation for it is pretty easy to follow.

So you could have something like this:

// This is assuming the two elements are hidden by default
if($.cookie('myCookie') === 'on')
    $("#s4-ribbonrow, #s4-titlerow").show();

s.click(function () {
    $("#s4-ribbonrow, #s4-titlerow").toggle();

    // Toggle cookie value
    if($.cookie('myCookie') === 'on')
        $.cookie('myCookie', 'off');
    else
        $.cookie('myCookie', 'on');
});

Upvotes: 1

Related Questions