In your code you are not checking whether the element is visible or not, you are checking whether it exists on the page.
From what I understand of your logic, the element always exists on the page, whether it is visible or not:
if ($('.buyButtonWrapper').length) { ... }
Never enter else
because the element is present in the DOM, only it is not visible to the user.
Solution
To check if the element is visible, in jQuery you can use the .is()
method. that will check the element "against" a selector, in this case the :visible
( English) :
// Se "Comprar" está visivel
if ($('.buyButtonWrapper').is(':visible')) {
$('.bloco-flags-desconto .flagsWrapper').hide(); // div flags descontos
$('.bloco-flags-desconto .flagsWrapper2').show(); // div flag Indisponivel
$('.ui-accordion').hide(); // accordion de parcelamento
}
// Se "Comprar" está escondido
else {
$('.bloco-flags-desconto .flagsWrapper').show();
$('.bloco-flags-desconto .flagsWrapper2').hide();
$('.ui-accordion').show();
}
Your code can still be optimized for:
// colocar elementos em cache
var $descontos = $('.bloco-flags-desconto .flagsWrapper'), // div flags descontos
$indisponivel = $('.bloco-flags-desconto .flagsWrapper2'), // div flag Indisponivel
$parcelamento = $('.ui-accordion'); // accordion de parcelamento
if ($('.buyButtonWrapper').is(':visible')) {
// Se "Comprar" está visivel
$descontos.hide();
$indisponivel.show();
$parcelamento.hide();
}
else {
// Se "Comprar" está escondido
$descontos.show();
$indisponivel.hide();
$parcelamento.show();
}
The second version of the code is preferable because if you have to update the selectors, you only need to tweak the values of the variables, you do not need to be doing multiple updates further down the middle of the code.