Results 1 to 4 of 4
Thread: building a simple jQuery plugin
-
April 11th, 2012, 09:13 AM #1
building a simple jQuery plugin
hello ..
I basically have a load of code using jQuery, that I now realise I have to add an if statement to every on('mouseenter') event I have depending on whether or not a boolean is true or false.
Ok - easy. But I wish to build a jQuery plugin (at the most simplest level), so that my query will continue and chain - or break. Is there a jQuery method that already exists that does that?
Otherwise::maybe there's easier ways - but it's interesting to build a plugin. And I have around 40 mouse overs ive got to plug an if statement into ...Code:var myBreak = true; jQuery.fn.makeOrBreak = function(v){ // break chain or query if(v != true){ }else{ // keep calm and carry on } }; // usage example $('#id').makeOrBreak(myBreak).hide(); // boolean is true so '#id' is allowed to chain and 'hide()'
Any pointers!?
PS am i in the right forum?!
-
April 11th, 2012, 06:06 PM #2
I would write that like this:
This evaluates as "If myBreak == true, hide the element"Code:myBreak && $("#id").hide();AS2 / AS3 / JS / JQUERY / (X)HTML / HTML5 / CSS / CSS3 / PHP
-
April 12th, 2012, 05:11 AM #3
handy tip! Shorthand is so confusing when you start learning code - but brilliant when sailing.
Still - is it possible to break out of the chain in jQuery?
-
April 12th, 2012, 05:42 AM #4Just return something else other than the jquery collection object in the function:Still - is it possible to break out of the chain in jQuery?
This will break the chain, but will obviously generate errors if there are function calls after it. If you know what methods are going to be called you can create a mock object that has the same methods. Your mock object to return if you knew the hide() method was going to be called would be something like this:Code:jQuery.fn.test = function() { return false; // Breaks the chain };
Code:var mock = { hide: function() { return this; } }; jQuery.fn.test = function() { if (true) { return mock; } else { return this; } };

Reply With Quote

Bookmarks