Prospal jQuery chained if statement
in Developing jQuery Core
•
11 years ago
Hi Guys,
I've not set up my profile on here yet, i've literally just thought of this and want to scribble it down before I forget! I've found myself in a situation several times whereby I'll have a large jQuery chain, then realise I need to implement something half way through the chain based on a condition, so this then means I need to split my chain in two, assign a variable to re-use etc. And so I checked documentation and I can't see anything that covers this already (but- If I'm wrong please do let me know!) and also, if you think I'm re-inventing the wheel again please let me know, but this is what I had in mind.
So say in this example I have (for whatever reason) two layout or color schemes. One, I want to include an animation on (Color Scheme A, and the other I want to display, but process some additional data when I do - Color Scheme B.)
Ok, so what I want to do - if my color scheme is 'a' - I want to set the text of an element to "value1", if I'm colour scheme 'b' then I want to text to be "value2".
My statement currently would have to look something like...
- var scheme = { id: 'a', background: '#000', value1: 'blah blah blah', value2: 'something else' };
- var header = $('#myheader').fadeIn(200);
- if (scheme.id == 'a') {
- header.text(scheme.value1);
- } else {
- header.text(scheme.value2);
- }
- header.animate({backgroundColor: scheme.background});
What I'm proposing would look a little like this:
- var scheme = {id: 'a', background: '#000', value1: 'blah blah blah', value2: 'something else'};
- $('#myheader').fadeIn(200)
- .if(scheme.id == 'a', $(this).text(scheme.value1), $(this).text(scheme.value2))
- .animate({backgroundColor: scheme.background});
As you can see, the number of lines of code required is halfed and has the benefit of not having to create extra variables.
It may be that, technically, it would have to be a seperate function, but even so I would prefer to have a nice chain and no variables.
Thoughts are welcome, and I won't take offence if it's a stupid idea

1