I have this snippet of code:
<script type="text/javascript">
$(window).load(function() {
if(!$.browser.msie){
$('#myDiv').animate({opacity: 1}, 300);
} else if ($.browser.msie) {
$('#myDiv').css({opacity:1});
}
});
</script>
How can I say the same thing using the " : something ? somethingElse "
syntax?
Thanks in advance?
I have this snippet of code:
<script type="text/javascript">
$(window).load(function() {
if(!$.browser.msie){
$('#myDiv').animate({opacity: 1}, 300);
} else if ($.browser.msie) {
$('#myDiv').css({opacity:1});
}
});
</script>
How can I say the same thing using the " : something ? somethingElse "
syntax?
Thanks in advance?
Share Improve this question asked Feb 12, 2013 at 14:55 Dimitri VorontzovDimitri Vorontzov 8,11412 gold badges51 silver badges78 bronze badges 4- 4 Don't use ternary operators as a generic if/else. Use them for simple assignments, that is what they are designed for. Real if/else across more lines are more readable. Embrace readability over code golf. – Quentin Commented Feb 12, 2013 at 14:57
- 2 The long and short of it is you probably don't want to. Nested ternary syntax gets very ugly. – David Kiger Commented Feb 12, 2013 at 14:57
-
2
... also the
else if ($.browser.msie) {
is redundant. A simpleelse {
would be enough. – Yoshi Commented Feb 12, 2013 at 14:57 - I agree with you 100%, guys, but in this case I actually do need the "code golf", for a certain reason. – Dimitri Vorontzov Commented Feb 12, 2013 at 14:58
2 Answers
Reset to default 7Not sure I got the question, however:
$.browser.msie ? $('#myDiv').css({opacity: 1}) : $('#myDiv').animate({opacity: 1}, 300);
Also, I'm not an expert of IE anymore, but I wonder if you could do something like:
$('#myDiv').animate({opacity: 1}, $.browser.msie ? 0 : 300);
That should be applied immediately, and made it more readable with an external variable:
var speed = $.browser.msie ? 0 : 300;
$('#myDiv').animate({opacity: 1}, speed);
Or something like that.
You can do it like this:
$(window).load(function() {
$.browser.msie ? $('#myDiv').css({opacity:1}); : $('#myDiv').animate({opacity: 1}, 300);
});
I wouldn't remend it for at least two reasons (browser sniffing, and readability), but you can.
Another way:
$(window).load(function() {
$('#myDiv')[$.browser.msie ? 'css' : 'animate']({opacity:1}, $.browser.msie ? undefined : 300);
});
...but that's even worse. ;-)