0

I have this jQuery if-statement working. Is there a more simple/elegant or less repetitive way to write it?

“If foo is visible, add this HTML element to #message, else add this other HTML element to #message.”

$(document).ready(function() {
    var $foo= $('#something');
    if ($foo.is(':visible')) {
        $('#message').html('<strong>Yes</strong>, message one.');
    }
    else {
        $('#message').html('<strong>No</strong>, message two.');
    }
});
  • 1
    You could use a ternary operator but it wouldn't be much shorter. Plus it'd be less readable. If you can edit the HTML, you could set the content of #message there and then just get rid of the else. – j08691 Dec 07 '18 at 17:09

2 Answers2

0

its already a small code block & I don't think there is much simplification possible but here you can define the $('#message') element in earlier line & use it in multiple places

$(document).ready(function() {
    var $foo= $('#something');
    var $messageBlock = $('#message');

    var $toShow = ($foo.is(':visible'))? '<strong>Yes</strong>, message one.' : '<strong>No</strong>, message two.';
    $messageBlock.html($toShow);

});
devsourav
  • 2,449
  • 1
  • 11
  • 18
0

You can set some variables to the variable parts of the message, and then substitute them in.

$(document).ready(function() {
    var $foo= $('#something'), yesno, msgnum;
    if ($foo.is(':visible')) {
        yesno = 'Yes';
        msgnum = 'one';
    }
    else {
        yesno = 'No';
        msgnum = 'two';
    }
    $('#message').html(`<strong>${yesno}</strong>, message ${msgnum}.`);
});

This makes the parallelism clearer.

Barmar
  • 741,623
  • 53
  • 500
  • 612