简体   繁体   中英

How to turn the following `.click` into a toggle?

The code:

  $('.ask-button').click(function() {
    $('.wpcf7-form').hide()
    $(this).css('margin-left', 0)
  })

I know I can't just do .toggle because in order to restore margin-left I have to include the original value ( 300px ).

What's the simplest way to turn the event above into a toggle?

You can use .toggle() to show hide the element and use .toggleClass() for toggling class with css margin left set to 0:

$('.ask-button').click(function() {
  $('.wpcf7-form').toggle()
  $(this).toggleClass('marginzero');
});

CSS:

.marginzero{
   margin-left:0;
}
    HTML
   <button class="ask-button">ask</button>
<div class="wpcf7-form">Sample text<div>
    js
  $('.ask-button').click(function() {
    $('.wpcf7-form').toggleClass('wpcf8-form')
  })
    css
   .wpcf7-form{ margin-left:300px; border:1px solid #ddd}
.wpcf8-form{ margin-left:0; border:1px solid #ddd}

use this link define width in class. it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM