Ad

JQuery Bind To Toggle Opacity On Elements

- 1 answer

I have the following JS which uses fadeToggle() which works fine however it does a display:none so the 3rd element which I always display jumps up so wondering if its possible to change to change the opacity to 0 so in theory the block is still there and nothing moves.

JS

$('.ty-banner__image-item.gt-banner').bind('touchstart touchend', function(e) {
    $(this).find('div.image .banner-overlay').fadeToggle('fade');
    $(this).find('.content h2, .content p:first-child, .content p:eq(1)').fadeToggle();
});

Can I toggle to set opacity to 0 on a toggle?

updated to use toggle class to add class fade which just changes opacity: 0 but need to fade it some how.

// mobile touch rubbish
    $('.ty-banner__image-item.gt-banner').bind('touchstart touchend', function(e) {
        $(this).find('div.image .banner-overlay').toggleClass('fade');
        $(this).find('.content h2, .content p:not(".button")').toggleClass('fade');
    });
Ad

Answer

You're right it sets display:none and the element space vanishes making the element after it takes its place, instead you need to use opacity with animate() function, just like this:

JS Fiddle 1

var toggleFlag = true;

$('#btn').on('click', function() {
  
  // if the toggle flag is true, we set the opacity to 0, 
  // else we set it to 1, and animate the opacity property
  var op = (toggleFlag) ? 0 : 1;
  $('#second-div').stop().animate({'opacity': op}, 500);
  
  // finally we switch the toggle flag value to keep in control  
  toggleFlag = !toggleFlag;
});
.divs {
  display: block;
  width: 150px;
  height: 100px;
  margin-bottom: 5px;
  background-color: orange;
}
#second-div {
  background-color: tomato;
}
#third-div {
  background-color: skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="first-div" class="divs"></div>
<div id="second-div" class="divs"></div>
<div id="third-div" class="divs"></div>
<button id="btn">animate</button>


Alternatively you can use .css() function wit


Alternatively you can use .css() function with CSS transition like this:

JS Fiddle 2

var toggleFlag = true;

$('#btn').on('click', function() {
  var op = (toggleFlag) ? 0 : 1;
  $('#second-div').css({'opacity': op, 'transition': 'opacity 0.5s'});
  toggleFlag = !toggleFlag;
});

UPDATE:

You need to bind it on either touchstart or touchend but not both because it'll response to both events and toggle its opacity too fast that the fade effect won't be noticeable.

JS Fiddle 3

Ad
source: stackoverflow.com
Ad