Unable to adjust image opacity using jQuery

I am attempting to change the opacity of an image based on a boolean flag. The image should have reduced opacity when the var pauseDisabled = true, and return to full opacity when pauseDisabled = false.

To demonstrate this, I have created a fiddle below. In this example, I am using a link to toggle the flag between true and false. However, the opacity does not seem to change as expected.

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');
    }
});

Answer №1

Your reasoning is flawed because the if condition will only execute once when the page loads. Instead, you should update the opacity every time the pauseDisabled flag changes in the click event handler. Here's a revised code snippet:

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>

Answer №2

Check out the latest update to your jsFiddle here:

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

The IF structure in your code was only triggered once, prior to any interaction with the link.

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

Answer №3

It is recommended to handle the opacity changes directly within the click event, eliminating the need for an if else statement outside of it.

        $(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;
  }
  })


});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The variable is unable to be accessed within the PHP function query

After passing a variable through ajax to a function within my php file "Cart_code.php", I encountered an issue where the variable was not accessible inside the function. Can you help me figure out why? Javascript $.ajax({ type: "POST", url: "incl ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

What steps should I take to ensure the privacy of this React Layout?

To ensure only authenticated users can access the layout component, we need to implement a check. const router = createBrowserRouter([ { path: "/", element: <Layout />, children: [ { path: "/", ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts). My goal is to transfer the option val ...

Achieving a consistent user experience across both mobile and desktop devices without using a separate mobile version or media queries

Is it possible to have the same URL website.com display completely different content depending on whether it is accessed from a mobile device or not? I am looking for a solution that does not involve using CSS media queries or creating a separate subdomai ...

Implementing an active class in Vue.js for the router-link component

I am facing an issue with my sidebar item becoming inactive when I click on a sublink inside a component. How can I prevent the active class from switching off? Here is my sidebar: <router-link to='/sub/success_tools_subscriptions' ...

"Troubleshooting: State array in ReactJS/NextJS not rendering correctly following setState

I am facing challenges with rendering my objects using .map() within React / NextJS. Within my code, I have a function where I retrieve images from Firebase Cloud Storage as shown below: getImages = () => { let firebase = loadFirebase() ...

Using JQuery Mobile to Incorporate Links into List Elements

Creating a mobile webpage tailored for college students involves assigning each student a unique id and an additional field. Both fields can be treated as strings, with the unique id being guaranteed to be unique, while the second field may or may not be u ...

Ways to retrieve element(s) and delete a specific class located in the DOM structure

This is my first time using stackoverflow and posting a question here! :] Can someone guide me on the best way to write JQuery code for this particular task? Task: My goal is to remove the 'active' CLASS from a nav element when it is active: ...

Extract specific elements from an array using Mongoose's $slice operator while still maintaining the

Currently, my task is to retrieve the total number of items in my News object and return a portion of those items as objects. While I have successfully implemented the $slice operator in my query, I am struggling to determine the original array size of the ...

Tag utilizing jQuery

Check out my JSFiddle. I'm looking to change the h2 name to a hashtag and update it when the next button is clicked. Does anyone have a solution for this? ...

Alert: Prop type error encountered - The prop 'open' must be defined in Snackbar component

Recently, I've been implementing jest snapshot tests into my application. The main focus is on the LoginForm component. render() { return ( ... <DynamicSnack dialogOpen={this.props.dialogOpen} snackOpen={this.props.sna ...

What is the best way to hide certain buttons from specific users in Angular using the If condition?

I am facing an issue with my array of blocked_users, where I need to hide certain buttons if a user is in the blocked_users list. Below is the code snippet from my angualr.component.html: <div *ngIf="!(userId in event.blocked_users)"> ...

jQuery AJAX request only successful after page refresh

I had previously asked a question similar to this one and received a working solution. However, as I continued with my beginner project and delved into AJAX, I encountered a new issue. It seems that the AJAX call is not successful until the page is reloade ...

Resolve the issue pertaining to the x-axis in D3 JS and enhance the y-axis and x-axis by implementing dashed lines

Can anyone assist with implementing the following features in D3 JS? I need to fix the x-axis position so that it doesn't scroll. The values on the x-axis are currently displayed as numbers (-2.5, -2.0, etc.), but I want them to be shown as percentag ...

Display an external function that highlights a Polyline in Google Maps V3

I want to create a Polyline that will be highlighted when I hover over an anchor tag. Everything is working fine with my code, as the Polyline is being drawn from a gps file. However, I am struggling to use 'setOptions' from an external function. ...

There seems to be a malfunction in the functionality of my Django template navbar

Within my project, I am utilizing two templates named base.html and contact.html. The contact.html template extends the base.html template, and these are the only two templates in use. When I navigate to the blog or about section by clicking on them, the p ...

What is causing the radio button's background color not to change after it is selected?

I've been searching and exploring various solutions, but I'm encountering some difficulties with the following scenario: There are a few restrictions: Cannot utilize Javascript or Jquery. Must be achieved using pure CSS. My objective is to chan ...

What is the best way to set a stationary background that scrolls on a responsive webpage?

I'm working on a responsive website with alternating sections featuring fixed background images where the content is meant to scroll over the image. However, I'm facing an issue on iOS where the background image zooms into a small section and sca ...