1

Want to apply same code on page load and on ajax complete. Below is the code

$(document).ajaxComplete(function() {
    showHideBlock();
});

$(document).ready(function() {
    showHideBlock();
});

function showHideBlock() {
    if ($('.reservationDetails').length == 1) {
        $('.user-reservation-info').show();
    } else {
        $('.user-reservation-info').hide();
    }
}

Any other better way of doing it?

Govind Samrow
  • 9,981
  • 13
  • 53
  • 90
Yogesh
  • 331
  • 1
  • 4
  • 10

1 Answers1

0

You could use method chaining and shorten the code that attaches the handlers for ready and ajaxComplete. You could avoid typing $('.user-reservation-info') twice by storing it in a variable. Also, since your if..else code is pretty simple, you could use a ternary operator.

$(document).ready(showHideBlock).ajaxComplete(showHideBlock);

function showHideBlock() {
    var userInfo = $('.user-reservation-info');
    $('.reservationDetails').length === 1 ? userInfo.show() : userInfo.hide();
}

You can also replace $('.reservationDetails').length === 1 with just $('.reservationDetails').length in the above code, if you're just doing it to check if .reservationDetails matches any elements in the DOM. But, if you specifically need length to be 1, then this can't be done.

maazadeeb
  • 5,922
  • 2
  • 27
  • 40
  • $(document).on('ajaxComplete ready', function() { if($('.reservationDetailsTitle').length) { $('.user-reservation-info').show(); }else{ $('.user-reservation-info').hide(); } }) I have used above and that worked! Anyways thanks for the answer :) – Yogesh Jul 13 '17 at 13:55