Attempting to alter an image with a click and then revert it back to its original state

I'm currently working on a feature that toggles an image when a specific class is clicked. The code I have so far successfully switches from 'plus.png' to 'minus.png' upon clicking, but I need it to switch back to 'plus.png' if the same class is clicked again.

Here's the jQuery snippet I'm using:

<script type="text/javascript">
$(document).ready(function () {
$('label.tree-toggler, .yellow').click(function () {
    $(this).parent().children('.yellow').attr('src', 'img/minus.png');
});
});

</script>

And here's the corresponding HTML:

<li><label class="tree-toggler nav-header">Safety and Emissions</label><img class="yellow" src="img/plus.png"><hr></hr>
   <ul class="nav nav-list tree">
      <li><a href="#" id="secLink">link<img class="yellow" src="img/chevron-right.png"></a><hr></hr></li>
      <li><a href="#" id="secLink">link<img class="yellow" src="img/chevron-right.png"></a><hr></hr></li>
   </ul>
</li>

If anyone could provide additional help or suggestions to enhance what I've already implemented, I would truly appreciate it!

Answer №1

To keep track of the image src you are using, you can add or remove a class. Here is an example:

$('label.tree-toggler, .yellow').click(function () {
    if ( $(this).parent().children('.yellow').hasClass('minus') ) {
        $(this).parent().children('.yellow').attr('src', 'img/plus.png').removeClass('minus');
    } else {
        $(this).parent().children('.yellow').attr('src', 'img/minus.png').addClass('minus');
    }     
});

Alternatively, you could utilize a data attribute and achieve a similar result:

$('label.tree-toggler, .yellow').click(function () {
    if ( $(this).parent().children('.yellow').data('current_src') == 'minus') {
        $(this).parent().children('.yellow').attr('src', 'img/plus.png').data('current_src', 'plus');
    } else {
        $(this).parent().children('.yellow').attr('src', 'img/minus.png').data('current_src', 'minus');
    }     
});

If you opt for the data attribute method, make sure to set data-current_src='minus' initially on the element.

Answer №2

My approach to solving this problem involves...

$(document).ready(
    function() {
        $(".className").click(
             var imgPath = $("img").attr('src');
             if(imgPath === "+.png") {  // comparing with current path
                // update the path to - 
             } else {
                // update the path to +
             }

); } );

I have not tested it yet, but that's the concept I'm going for

Answer №3

My suggestion would be to include an additional class such as .active or .shown using JQuery when switching the image. This way, you can easily determine the current state of the item you are selecting.

The JQuery code might resemble something like this:

$('label.tree-toggler, .yellow').click(function () {
   // Check if the active class is NOT present
   if( !( $(this).parent().children('.yellow').hasClass('active') ) ) {
      // Add the active class and change the image source
      $(this).parent().children('.yellow').addClass('active').attr('src','img/minus.png');
   }
   else 
      $(this).parent().children('.yellow').removeClass('active').attr('src', 'img/plus.png');
});

In this scenario, the active class is used to indicate the image's current state. By clicking on it, you will alter the image and set the flag.

Upon each click, the flag is evaluated and behaves accordingly. I hope this explanation proves beneficial! I'm still relatively new to S.O. =.="

Answer №4

If you are looking to implement this in JavaScript, my suggestion would be to follow these steps:

  • Place your initial image in the src attribute
  • Add your alternative image in the data-alternative attribute

Here is an example of how it should look:

<li>
    <label class="tree-toggler nav-header">Safety and Emissions</label>
    <img class="yellow" src="img/plus.png" data-alternative="img/minus.png"><hr></hr>
    <ul class="nav nav-list tree">
        <li><a href="#" id="secLink">link<img class="yellow" src="img/chevron-right.png"></a><hr></hr></li>
        <li><a href="#" id="secLink">link<img class="yellow" src="img/chevron-right.png"></a><hr></hr></li>
    </ul>
</li>

And here is the JavaScript code:

<script type="text/javascript">
$(document).ready(function () {
    $('label.tree-toggler, .yellow').click(function () {
        var yellow = $(this).parent().children('.yellow').first();
        var alternative = yellow.data('alternative');
        yellow.data('alternative', yellow.attr('src'))
              .attr('src', alternative );
    });
});

</script>

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

What is the process for enabling multiple consumers to subscribe to a shared topic in RabbitMQ and receive identical messages?

Although there is a similar question with an answer here, I remain uncertain whether the limitation lies in RabbitMQ's capabilities or if I simply need to conduct further research. Coming from a JS/Node background where the event pub/sub pattern func ...

Can floating elements be disregarded by block elements?

According to W3C, the behavior of floating elements is such that: When a float is present, non-positioned block boxes that come before and after the float flow vertically as if the float doesn't exist. However, line boxes positioned next to the fl ...

Javascript has ceased functioning on the current server, however it is operational on a different

Need a hand with this tricky issue. The company I'm with has its own website. I've been updating pages on the site for the past few days. After finishing my updates and trying to upload the site, all of a sudden, the JavaScript stopped working. ...

Is it possible to combine two conditions using CSS?

Hello, I have a question about CSS. In my navigation bar, I have 3 links with different styles: #p1 { font-family: Arial, Helvetica, sans-serif; font-size: 13px; line-height: 45px; font-weight: bolder; color: #999999; text-dec ...

What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question"); const faqContents = document.getElementsByClassName("faq-content"); for (item of faqItems) { console.log(item); item.addEventListene ...

What strategies can be utilized to raise the max-height from the bottom to the top?

I am facing the following coding challenge: <div id = "parent"> <div id = "button"></div> </div> There is also a dynamically generated <div id="list"></div> I have successfully implem ...

Send information from the textbox

I am trying to extract data from an input field and use it to create a QR code. While passing the value as text works, I am facing issues with passing the actual input value. Does anyone have a straightforward example of this process? import React, {Comp ...

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

Issue with Material-UI Slider not updating the color of the active range

I am currently working on a Range Slider component that ranges from zero to ten. The issue I am facing is that the values inside the range are not getting colored as expected. Here is My Custom Slider Component: export function VoteRange({ voteRange, set ...

Tips for positioning HTML elements at the exact mouse location as it moves, without any delay?

Currently, I am in the process of developing a web-based drawing application that does not rely on using a canvas. My decision to avoid using a canvas is because I plan to incorporate CSS Keyframes into the HTML elements upon placement. This approach allow ...

When FullCalendar eventRender is called, it can cause the browser tab to become

I'm working with the FullCalendar plugin within AngularJs. Everything is functioning properly. However, when I add background color, image, tooltip, and label for each event in the eventRender event, it causes the browser tab to freeze for a few seco ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...

When performing an Angular HTTP post, additional parameters are automatically included in the request

Within a directive, I have the following code block: scope.progressCourse = -> req_data = course_id: scope.course.id success: true $http.post( "<%= Rails.application.routes.url_helpers.progress_course_path %>", req_data ).t ...

JavaScript function to provide a range of numbers based on a specified number and step value

I am looking for a solution to dynamically generate content based on the number of slides/steps using JavaScript. Any suggestions on how to best achieve this? Thanks in advance! switch(this.currentSlide) { case 1: return '1-12'; ...

Changing the value of a user object's variable in Django

I have been working on implementing a feature that allows users to edit their personal information in a Django project using Django forms. However, after entering new values in the form and hitting enter, the user is redirected back to the main profile pag ...

No matter how much I try, the text refuses to align with the top-left corner

I have been working on creating a loading screen, but I am facing an issue with aligning the h1 tag selected to the top left. As a young developer at the age of 13, I am quite confused. I attempted to use the following CSS properties: vertical-align: top; ...

What is the best way to update information in a mongoose document using the _id field?

Although it may sound like a typical question, I've already conducted research and couldn't find a solution. I'm currently working on developing a discord bot and I don't have much experience in this area. The issue I keep encountering ...

Tips for converting an object into parameters for ng-include

What is the best way to create a serialized array of objects that can be used as parameters for ng-include in order to dynamically load data from the server? Using Angular controller and params with requests: app.controller("MyCtrl", function($scope) { ...

Find your favorite artist on Spotify through the search function

Recently, I stumbled upon this intriguing demo showcasing how to search for an artist using the Spotify API. However, despite several attempts, I have been unable to make it function properly. Can anyone provide any tips or guidance on making this work suc ...

hybrid application combining AngularJS with Angular 17 and above versions

I have been attempting to set up a hybrid environment with both AngularJS and Angular 1.7+ running side by side. I diligently followed all the guidelines and even created a custom webpack configuration to bundle my AngularJS and Angular files together. The ...