Search code examples
javascriptjqueryhtmlcssopacity

Can't change opacity of image with jQuery


I'm trying to get a image to change opacity based on a boolean flag. It should drop opacity when the var pauseDisabled = true and go back to a value of 1 when pauseDisabled = false.

I created the fiddle below to simulate what I'm attempting. In this example I simply am trying to use a link to control the on/off switch. It won't drop opacity however and I'm not sure what I'm doing wrong.

JS Fiddle: https://jsfiddle.net/w51Lxvjp/8/

<div class="pause">
    <a class="pause-btn">
        <img class="pause-img" src="https://cdn3.iconfinder.com/data/icons/buttons/512/Icon_4-512.png">
    </a>
</div>

<a class="disabler" href="#">Disable Button</a>
$(document).ready(function() {
    var pauseDisabled = false;

    $('.disabler').click(function() {
        pauseDisabled = true;
    })

    if (pauseDisabled === true) {
        $('.pause').css('opacity', '0.2');
    } else if (pauseDisabled === false) {
        $('.pause').css('opacity', '1');
    }
});

Solution

  • Your logic is flawed as the if condition will only run once on load of the page. Instead you need to set the opacity each time the pauseDisabled flag is toggled within the click event handler. Try this:

    jQuery($ => {
      let pauseDisabled = false;
    
      $('.disabler').click(() => {
        pauseDisabled = !pauseDisabled;
        $('.pause').css('opacity', pauseDisabled ? '0.2' : '1');
      })
    });
    img { width: 250px; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <div class="pause">
      <a class="pause-btn">
        <img class="pause-img" src="https://cdn3.iconfinder.com/data/icons/buttons/512/Icon_4-512.png">
      </a>
    </div>
    <a class="disabler" href="#">Disable Button</a>