How not to accumulate effects in Hide and Show

0

By clicking on the Fade button the div disappears, and then clicking on the UnFade button causes the div to reappear. So good.

If you then click the Fade button again, the div disappears, appears and disappears again.

If you then click the UnFade button, the div appears, disappears, and appears again.

If you then click fade again, the div disappears, appears, disappears, appears and disappears again.

So if you click alternately 10 times on Fade and UnFade you will see that the div goes back and forth 10 times. I wonder if you have a way to avoid this. If you click fade it disappears and Unfade appears regardless of the number of times it was clicked alternately.

function functionHide() {
  $("div").hide(1000);
}
function functionShow() {
  $("div").show(1000);
}


$( "#id1" ).click(function() {
  $( "body" ).click(functionHide);
});

$( "#id2" ).click(function() {
  $( "body" ).click (functionShow);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><buttonid="id1">Fade</button>
<button id="id2">UnFade</button>

<div>Click!</div>
    
asked by anonymous 08.04.2017 / 04:30

2 answers

1

The $ ("body"). click (...) in your code does not make sense, mainly being inside another click.

What your code was doing was, each time you clicked the button, you would get a new event handler to the body element, which was to be executed when the body was clicked. So with every click the action was executed once more, because the event handlers were being added and the old ones were still there.

$(document).ready(function() {
  function functionHide() {
    $("div").hide(1000);
  }
  function functionShow() {
    $("div").show(1000);
  }


  $( "#id1" ).click(functionHide);

  $( "#id2" ).click(functionShow);
})
    
08.04.2017 / 04:53
1

I've already visualized your problem friend.

function functionHide() {
    $("div").hide(1000);
}

function functionShow() {
    $("div").show(1000);
}

The declaration of the above functions are ok. The problem is how you are doing to call them. From what I understand, you have a button that when clicking, you hide something or displays, through the previously declared functions. Soon it would look like this:

$("#id1").click(function() {
    functionHide();
});

$("#id2").click(function() {
    functionShow();
});

Your error was trying to complicate the call of functions using a $ ("body").

function functionHide() {
  $("div").hide(1000);
}
function functionShow() {
  $("div").show(1000);
}

$("#id1").click(function() {
    functionHide();
});

$("#id2").click(function() {
    functionShow();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><buttonid="id1">Fade</button>
<button id="id2">UnFade</button>

<div>Click!</div>
    
08.04.2017 / 15:32