Need help adding jQuery cookie plugin to this please

http://www.websitecodetutorials.com/code/jquery-plugins/how-to-jQuery-wiggle-plugin-demo.php. I see the cookie plugin is copy past. I just don’t know how to properly add it to this. Thus is not for the demo. It’s for another site of mine. The demo just makes it easy to see the code. I want the image to wiggle upon first visit. And not wiggle again for 30 days or until they clear cookies. Thanks!

There is a jQuery cookie plugin at https://github.com/carhartl/jquery-cookie which can help to simplify things.

WIth that, this would be as easy as doing:


function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
        return false;
    }
    return true;
}

if (allowedToWiggle() {
    doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});
}

Thank you Paul. OK I just added the cookie plugin and your code but does not seem to work. Surely I’m missing something. Here is the whole code. What am I missing? Thnaks!

<!DOCTYPE HTML><html><head><meta charset="UTF-8">
<title>How To jQuery Wiggle Plugin Demo</title>
<style type="text/css">
div.wiggle {
background:url(../images/the-wiggles.jpg);
height:186px;
width:250px;
margin:30px 0 0 30px;
}
</style>
</head>
<body>
	<h1>How To jQuery Wiggle Plugin Demo</h1>
	<p><a href="how-to-jQuery-wiggle-plugin.php">&laquo; Back To Tutorial</a></p>
	<p>The script wiggles for <strong>1 second</strong>, every <strong>3 seconds</strong>, for a total of <strong>30 seconds</strong>, and <strong>aborts if hovered over</strong>.</p>
	<div class="wiggle"></div>
	<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
	<script type="text/javascript">
/* jQuery Wiggle - http://www.class.pm/files/jquery/jquery.wiggle/demo/ */
(function($) {
    $.fn.wiggle = function(method, options) {
        options = $.extend({
            degrees: ['2','4','2','0','-2','-4','-2','0'], /* Movement Measurements */
            delay: 30, /* Wiggle Speed */
            limit: null,
            randomStart: true,
            onWiggle: function(o) {},
            onWiggleStart: function(o) {},
            onWiggleStop: function(o) {}
        }, options);
        var methods = {
            wiggle: function(o, step){
                if (step === undefined) {
                    step = options.randomStart ? Math.floor(Math.random() * options.degrees.length) : 0;
                }
                if (!$(o).hasClass('wiggling')) {
                    $(o).addClass('wiggling');
                }
                var degree = options.degrees[step];
                $(o).css({
                    '-webkit-transform': 'rotate(' + degree + 'deg)',
                    '-moz-transform': 'rotate(' + degree + 'deg)',
                    '-o-transform': 'rotate(' + degree + 'deg)',
                    '-sand-transform': 'rotate(' + degree + 'deg)',
                    'transform': 'rotate(' + degree + 'deg)'
                });
                if (step == (options.degrees.length - 1)) {
                    step = 0;
                    if ($(o).data('wiggles') === undefined) {
                        $(o).data('wiggles', 1);
                    }
                    else {
                        $(o).data('wiggles', $(o).data('wiggles') + 1);
                    }
                    options.onWiggle(o);
                }
                if (options.limit && $(o).data('wiggles') == options.limit) {
                    return methods.stop(o);
                }
                o.timeout = setTimeout(function() {
                    methods.wiggle(o, step + 1);
                }, options.delay);
            },
            stop: function(o) {
                $(o).data('wiggles', 0);
                $(o).css({
                    '-webkit-transform': 'rotate(0deg)',
                    '-moz-transform': 'rotate(0deg)',
                    '-o-transform': 'rotate(0deg)',
                    '-sand-transform': 'rotate(0deg)',
                    'transform': 'rotate(0deg)'
                });
                if ($(o).hasClass('wiggling')) {
                    $(o).removeClass('wiggling');
                }
                clearTimeout(o.timeout);
                o.timeout = null;
                options.onWiggleStop(o);
            },
            isWiggling: function(o) {
                return !o.timeout ? false : true;
            }
        };
        if (method == 'isWiggling' && this.length == 1) {
            return methods.isWiggling(this[0]);
        }
        this.each(function() {
            if ((method == 'start' || method === undefined) && !this.timeout) {
                methods.wiggle(this);
                options.onWiggleStart(this);
            }
            else if (method == 'stop') {
                methods.stop(this);
            }
        });
        return this;
    }
})(jQuery);

/* Fire Wiggle 1000 = how long each wiggle, 3000 = time between each wiggle, 31000 = total duration of wiggle */
function wiggleForOneSecond(t){
    t.wiggle();
    setTimeout(function(){t.wiggle('stop')},1000)
  }
  $(document).ready(function(){
    var thingToWiggle = $('.wiggle');
    var s = setInterval(function(){wiggleForOneSecond(thingToWiggle)},3000);
    setTimeout(function(){window.clearInterval(s)},31000)
    thingToWiggle.hover(function(){
      window.clearInterval(s)
    });
  });
	</script>
	<script type="text/javascript">
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as anonymous module.
		define(['jquery'], factory);
	} else {
		// Browser globals.
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\\+/g;

	function raw(s) {
		return s;
	}

	function decoded(s) {
		return decodeURIComponent(s.replace(pluses, ' '));
	}

	function converted(s) {
		if (s.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape
			s = s.slice(1, -1).replace(/\\\\"/g, '"').replace(/\\\\\\\\/g, '\\\\');
		}
		try {
			return config.json ? JSON.parse(s) : s;
		} catch(er) {}
	}

	var config = $.cookie = function (key, value, options) {

		// write
		if (value !== undefined) {
			options = $.extend({}, config.defaults, options);

			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}

			value = config.json ? JSON.stringify(value) : String(value);

			return (document.cookie = [
				config.raw ? key : encodeURIComponent(key),
				'=',
				config.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path    ? '; path=' + options.path : '',
				options.domain  ? '; domain=' + options.domain : '',
				options.secure  ? '; secure' : ''
			].join(''));
		}

		// read
		var decode = config.raw ? raw : decoded;
		var cookies = document.cookie.split('; ');
		var result = key ? undefined : {};
		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decode(parts.shift());
			var cookie = decode(parts.join('='));

			if (key && key === name) {
				result = converted(cookie);
				break;
			}

			if (!key) {
				result[name] = converted(cookie);
			}
		}

		return result;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		if ($.cookie(key) !== undefined) {
			// Must not alter options, thus extending a fresh object...
			$.cookie(key, '', $.extend({}, options, { expires: -1 }));
			return true;
		}
		return false;
	};

}));

/* ---- fire ----- */
function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
        return false;
    }
    return true;
}

if (allowedToWiggle() {
    doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});
}
</script>
</body>
</html>


Yes indeed - the code I wrote was just an example. You’ll need to customize it to work in your particular situation.
For example - the doWiggleStuff() function is where you would trigger the wiggle.

Well there are plenty of examples on the web. My question was how to incorporate it into mine. I was just not in the mood to sit down and stare at all the examples until I figured it out. Hoping you could just tell me. :slight_smile: being lazy I guess.

Edit: actually I’m not finding any that spell it out for me in a way that makes sense. So how do I add that function to my code?

Wouldn’t you just add it here Eric?


$(document).ready(function () {
 [B] function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
        return false;
    }
    return true;
}[/B]
 [B] if (allowedToWiggle()) {
    //doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});
[/B]
				var thingToWiggle = $('.wiggle');
    var s = setInterval(function () {
        wiggleForOneSecond(thingToWiggle)
    }, 3000);
    setTimeout(function () {
        window.clearInterval(s)
    }, 31000)
    thingToWiggle.hover(function () {
        window.clearInterval(s)
    });
 [B]}[/B]
});


Thanks Paul I will try that out next Monday when I get home from vacation.

OK I’m ready to tackle this. Let me see how your example works Paul and I’ll let you know…

Good morning. Was there a reason you removed the first function block from your example Paul? I was just comparing your example to my code in the demo and noticed it gone.


[B][COLOR="#FF0000"]function wiggleForOneSecond(t){
    t.wiggle();
    setTimeout(function(){t.wiggle('stop')},1000)
  }[/COLOR][/B]
[B]function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
        return false;
    }
    return true;
}
  if (allowedToWiggle()) {
    //doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});[/B]
  $(document).ready(function(){
    var thingToWiggle = $('.wiggle');
    var s = setInterval(function(){wiggleForOneSecond(thingToWiggle)},3000);
    setTimeout(function(){window.clearInterval(s)},31000)
    thingToWiggle.hover(function(){
      window.clearInterval(s)
    });
  });

If you mean me (as there are 2 Pauls in this thread :)) then I didn;t remove anything.

You had this code:


$(document).ready(function () {
    var thingToWiggle = $('.wiggle');
    var s = setInterval(function () {
        wiggleForOneSecond(thingToWiggle)
    }, 3000);
    setTimeout(function () {
        window.clearInterval(s)
    }, 31000)
    thingToWiggle.hover(function () {
        window.clearInterval(s)
    });
});


and I said insert the cookie function above it here:


$(document).ready(function () {
[B]  function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
        return false;
    }
    return true;
}
  if (allowedToWiggle()) {
    //doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});[/B]

var thingToWiggle = $('.wiggle');
    var s = setInterval(function () {
        wiggleForOneSecond(thingToWiggle)
    }, 3000);
    setTimeout(function () {
        window.clearInterval(s)
    }, 31000)
    thingToWiggle.hover(function () {
        window.clearInterval(s)
    });
 }
});


The other Paul can confirm if that is correct though :slight_smile:

Paul OB :slight_smile:

hmm. maybe I’m missing something. but copied from here http://www.websitecodetutorials.com/code/jquery-plugins/how-to-jQuery-wiggle-plugin.php. The fire wiggle part at the end.

function wiggleForOneSecond(t){
    t.wiggle();
    setTimeout(function(){t.wiggle('stop')},1000)
  }
  $(document).ready(function(){
    var thingToWiggle = $('.wiggle');
    var s = setInterval(function(){wiggleForOneSecond(thingToWiggle)},3000);
    setTimeout(function(){window.clearInterval(s)},31000)
    thingToWiggle.hover(function(){
      window.clearInterval(s)
    });
  });

Then we add your example code… and there are two function blocks. Correct?? So like…

function wiggleForOneSecond(t){
    t.wiggle();
    setTimeout(function(){t.wiggle('stop')},1000)
  }
function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
        return false;
    }
    return true;
}
  if (allowedToWiggle()) {
    //doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});
  $(document).ready(function(){
    var thingToWiggle = $('.wiggle');
    var s = setInterval(function(){wiggleForOneSecond(thingToWiggle)},3000);
    setTimeout(function(){window.clearInterval(s)},31000)
    thingToWiggle.hover(function(){
      window.clearInterval(s)
    });
  });

I’m sure that would work. Sorry to convolute the question here. Just like make sure I got it right. Thank you

OK lets make this easier. Here is my exact compressed code (cant uncompress it sorry) that fires the wiggle.

/* Fire jQuery Wiggle - 1500 = how long each wiggle, 5000 = time between each wiggle, 21000 = total duration of wiggle */
function wiggleForOneSecond(a){a.wiggle();setTimeout(function(){a.wiggle("stop")},1500)}$(document).ready(function(){var b=$(".wiggle");var a=setInterval(function(){wiggleForOneSecond(b)},10000);setTimeout(function(){window.clearInterval(a)},31000);b.hover(function(){window.clearInterval(a)})});

  1. I throw in the cookie plugin https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js. 2) Then how exactly do I add the cookie bit the block above? I tried adding what you showed Paul OB but it stopped wiggling all together. Thank you for your time :slight_smile:

Hey Eric,

You can uncompress it. Here, for example:

/* Fire jQuery Wiggle - 1500 = how long each wiggle, 5000 = time between each wiggle, 21000 = total duration of wiggle */

function wiggleForOneSecond(a) {
    a.wiggle();
    setTimeout(function () {
        a.wiggle("stop")
    }, 1500)
}
$(document).ready(function () {
    var b = $(".wiggle");
    var a = setInterval(function () {
        wiggleForOneSecond(b)
    }, 10000);
    setTimeout(function () {
        window.clearInterval(a)
    }, 31000);
    b.hover(function () {
        window.clearInterval(a)
    })
});

You would implement Paul’s code thus:

function allowedToWiggle() {
  if ($.cookie('hasRecentlyWiggled')) {
    return false;
  }
  return true;
}

function wiggleForOneSecond(a) {
  a.wiggle();
  setTimeout(function () {
      a.wiggle("stop")
  }, 1500)
}

if (allowedToWiggle()) {
  var b = $(".wiggle");
  var a = setInterval(function () {
     wiggleForOneSecond(b)
  }, 10000); 
  setTimeout(function () {
      window.clearInterval(a)
  }, 31000);
  b.hover(function () {
      window.clearInterval(a)
  })
  $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});
} 

Hi,

All you needed to do was add and wrap this little piece of code:


  function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
        return false;
    }
    return true;
}
  if (allowedToWiggle()) {
    //doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});



}



In to this block which was at the end of the wiggle js:


$(document).ready(function(){var b=$(".wiggle");var a=setInterval(function(){wiggleForOneSecond(b)},5000);setTimeout(function(){window.clearInterval(a)},31000);b.hover(function(){window.clearInterval(a)})});

So that teh above snippet looks like this:


$(document).ready(function () {
  function allowedToWiggle() {
    if ($.cookie('hasRecentlyWiggled')) {
								return false;
    }
    return true;
}
  if (allowedToWiggle()) {
    //doWiggleStuff();
    $.cookie('hasRecentlyWiggled', 'yes', {expires: 30});

				var thingToWiggle = $('.wiggle');
    var s = setInterval(function () {
        wiggleForOneSecond(thingToWiggle)
    }, 3000);
    setTimeout(function () {
        window.clearInterval(s)
    }, 31000)
    thingToWiggle.hover(function () {
        window.clearInterval(s)
    });
 }
});


Here it is working:

http://www.pmob.co.uk/temp/wiggle.htm

Note that once you have tested it then it won’t work again unless you delete the cookie from the browser.

Man I need a js class. I just don’t have the patients for it anymore. I’ve been saying that for the last 7 years lol

Hey Pullo :slight_smile: Why no doc.ready? I assume there is a reason it’s not needed?

Hey Eric,
I always used to include it for good measure, but since I actually looked in to what it does, it seems it is hardly ever needed if you position your JS just before the closing <body> tag.
This also gives the page the impression of loading faster as an added bonus.

Check out this thread for a more detailed explanation (thanks to felgall)

Ok that all sounded good. I have like 5 or so instances of doc.ready in my all in one js file. When removing doc ready do i just remove it, or it and a closing tag at the bottom of each block? Thanks.

You don’t need five calls to doc.ready()
At the very least move all of these into one.

E.g. this:

$(document).ready(function(){
  // Do some stuff
});

$(document).ready(function(){
  // Do some more stuff
});

Can become this:

$(document).ready(function(){
  // Do some stuff
  // Do some more stuff
});

And very probably this:

    <script>
      // Do some stuff
      // Do some more stuff
    </script>
  </body>
</html>

or this:

    <script src="link-to-file-where-stuff-is-done"></script>
  </body>
</html>

HTH

I can’t organize it like that. I have to do plugin - next plugin - etc or I’ll forget what what. But if I want to lose the doc.ready do I remove the whole block like so…

$(document).ready(function(){
// Do some stuff
});

becomes just

// Do some stuff