2

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'); } }); 
1
  • You have to put the if statement in the click function. Commented May 18, 2016 at 19:54

3 Answers 3

4

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>

Sign up to request clarification or add additional context in comments.

Comments

0

Your jsFiddle has been updated:

https://jsfiddle.net/w51Lxvjp/15/ 

Essentially, your IF structure was executed only once, before any click on the link.

$('.disabler').click(function() { pauseDisabled = !pauseDisabled; if (pauseDisabled === true) { $('.pause-img').css('opacity', '0.2'); } else { $('.pause-img').css('opacity', '1'); } }) 

Comments

0

No need to create this if else outside of this click event . You can change the opacity directly inside the click event .

 $(document).ready(function() { var pauseDisabled = false; $('.disabler').click(function() { if (pauseDisabled === false) { $('.pause').css('opacity', '0.2'); pauseDisabled = true; } else if (pauseDisabled === true) { $('.pause').css('opacity', '1'); pauseDisabled = false; } }) }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.