How do I stop the function again when I don't want to? (JQuery)

There are a lot of things wrong with my js code. When I hit Show a few times, # box-1 just keeps going further and further down. The same thing happens for # box-2 when I click Hide a few times. How do I stop this?

I would also like to add how to make the boxes "fade out" when they show and hide? I seem to be able to get it to work when it shows. Also I don't want to use the toggle button, I want to use 2 buttons because I am experimenting with something.

Here's a JSFiddle link

Thank you for your time:)

$(document).ready(function(){
$('a#hide').click(function(){
    $('#box1').hide().animate({'top': '-=155px', opacity: 0}, 500);
    $('#box2').show().animate({'top': '+=155px', opacity: 1}, 500); 
})

$('a#show').click(function(){
    $('#box1').show().animate({'top': '+=155px', opacity: 1}, 500);       
    $('#box2').hide().animate({'top': '-=155px', opacity: 0}, 500);
}) });

      

EDIT:

I got the code working the way I wanted everyone thanks to you guys! All of your answers are not exactly what I was looking for, but with all of your answers, I definitely got it working. So many thanks to all of you for answering and helping me :) I really appreciate it.

Here's an updated JSFiddle link https://jsfiddle.net/vr1u0wzu/83/

Thanks again to people. Hooray!

+3


source to share


3 answers


You may try:



function hideIt() {
  $('#box1').hide().animate({'top': '-=155px', opacity: 0}, 500);
  $('#box2').show().animate({'top': '+=155px', opacity: 1}, 500); 
  $('a#show').one('click', showIt);
}
function showIt() {
  $('#box1').show().animate({'top': '+=155px', opacity: 1}, 500);       
  $('#box2').hide().animate({'top': '-=155px', opacity: 0}, 500);
  $('a#hide').one('click', hideIt);
}

$(document).ready(function(){
  $('a#hide').one('click', hideIt);
});

      

+1


source


$(document).ready(function(){
    $('a#hide').click(function(){
    $('#box1').fadeOut();
    $('#box2').show().animate({'top': '155px', opacity: 1}, 500); 
    })

    $('a#show').click(function(){
    $('#box1').show().animate({'top': '155px', opacity: 1}, 500);       
    $('#box2').fadeOut();
  })
 });

      



hope this helps you. Don't forget to check if this is what you are looking for .. =)

+1


source


I am assuming you only want to display one drawer at a time. Here is a solution https://jsfiddle.net/vr1u0wzu/55/ .

If you cannot understand, please indicate your doubts. I have used CSS classes to achieve fadein and fadeout. This is the easiest way to do it. Although you can use the functions .show()

, .hide()

, .fadeOut()

, .fadeIn()

the jquery to achieve the same.

The reason the box kept moving down is because you didn't reset it to the top level to 0px;

+1


source







All Articles