Use of fadein and fadeOut on click() with jQuery

Asked

Viewed 69 times

2

I wanted to make a certain element disappear with the fadeOut() command when clicking on a button, and when clicking again, it appeared with fadein(). I tried to do something like:

    $('nav.mobile h3.shopping-bag').fadeOut();
    if ($('nav.mobile h3.shopping-bag').fadeOut() === true){
         $('nav.mobile h3.shopping-bag').fadeIn();
    } else {
         $('nav.mobile h3.shopping-bag').fadeOut();
    }
});

However, the logic or some command sequence is wrong. Can anyone help me? Ps: I would like something similar to swap and unlock the color of an element using the same logic when I click.

1 answer

1


You need to have a control variable to know if the element is visible or not. The method fadeOut() does not return a boolean as you expect, it just hides the element.

let estaVisivel = true; // No começo, ele está visível
$("button").click(function() {  // A cada clique, faz um fadeOut ou fadeIn
  if (estaVisivel) {
  	$('p').fadeOut();   // Se estiver visível, fadeOut
  } else {
  	$('p').fadeIn();    // Senão, fadeIn
  }
  estaVisivel = !estaVisivel; // estaVisivel passará a ter o valor contrário (se era true, será false, se era false, será true)
});
<button>Clique</button>
<p>Olá</p>

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

  • Oh yes, now I understand. Thank you so much for your help! I will apply the solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.