skip to Main Content

I’m trying it with this one, but sometimes the .click() just automaticly does the command not waiting for actual click.

var x = 0; 

if ($('#business').click() && (x = 0)) {
  $('#business').css('height', '500px');
  x = 1;
} else if ($('#business').click() && (x = 1)) {
  $('#business').css('height', '100px');
  x = 0;
}

I can resize it with the below code, but unfortunately dont know how to change back on click again.

$('#business').click(function(){
  $('#business').css('height', '500px')
})

2

Answers


  1. If you use $('#business').click(), it will actually simulate a click on your event.

    If you want to have an action done on the click on your div, you should use your 2nd form:

    $('#business').click(function(){
      // Do whatever I want on click
    })
    

    In order to be able to change the height from one value to the other, you have two way for doing that:

    1. Use a data-* property on your div element, test its value and set your height accordingly (and change the value of this property)
    2. Get the current height of your element and change it accordingly

    For instance, you could do something like this:

    $('#business').click(function(){
      if($('#business').css('height') === "500px")
        $('#business').css('height', '100px');
      else
        $('#business').css('height', '500px');
    })
    
    Login or Signup to reply.
  2. Just toggle a class so there is no worrying about what state it should be in. Avoid setting css style properties directly in JavaScript.

    $(".foo").on("click", function () {
      $(this).toggleClass('active');
    });
    .foo {
      height: 100px;
      border: 1px solid #CCC;
    }
    
    .foo.active {
      height: 200px;
      background-color: yellow;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="foo">1</div>
    <div class="foo">2</div>
    <div class="foo">3</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search