kylebuzzy1
kylebuzzy1

Reputation: 17

If/Else Statement Assistance

I need to make this line of code into an If/Else statement for a school project and cannot figure out how to do so. The button currently triggers the picture to show on the page, but I cannot figure out how to also make it hide on button click using an If/Else statement.

$('#showA').on('click', function() {
    $('#house1').css('opacity', 1).fadeIn('slow');
  });

Upvotes: 0

Views: 74

Answers (2)

prasanth
prasanth

Reputation: 22500

No need a if/else - just use with fadeToggle() of Jquery function .

$('#showA').on('click', function() {
    $('#house1').fadeToggle('slow');
  });

Refer the Demo snippet

 $('#showA').on('click', function() {
        $('#house1').fadeToggle('slow');
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="showA">show</p>
<h3 id="house1">hello</h3>

Use with if/else for OP required

  1. adding the fadeIn and fadeOut depend on count variable
  2. if the element was hidden count reset to 0
  3. At the time of click count == 0 element will be hidden

var count=0;
$('#showA').on('click', function() {
           if(count == 0){
            $('#house1').fadeOut('400');
            count++
            }
            else {
            $('#house1').fadeIn('400');
            count=0
            }
          });
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id="showA">show</p>
    <h3 id="house1">hello</h3>

Upvotes: 1

kind user
kind user

Reputation: 41893

There's a jQuery function responsible for it - fadeToggle.

Note: fade function already operates the opacity property, you don't need to include it.

$('#showA').on('click', function() {
    $('#house1').fadeToggle('slow');
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='showA'>click</button>
<p id='house1' hidden>Hi</p>

Upvotes: 0

Related Questions