Image does not change when you click it, only in the text

Asked

Viewed 26 times

0

I’m having a problem, I have a project with several collapses and to indicate opening and closing of the collapses, I put an arrow to the right and while clicking on the text, it turns down and the Collapse opens, however, if you click on the arrow itself, Collapse opens but the image does not change. I wish she’d change along, like I could do?

Collapse HTML code

        <h1 index="1" class="collapsed change" data-toggle="collapse" data-parent="#accordion" 
        href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" ng-click="alert_step2()">

        <img index="1" class="change img-change" src="assets/img/arrow_right.png"
        style="width: 20px; height: 25px">Step 2 - Acknowledge Your Strengths (highest scores)</h1>

                        </h1>

JS code for image exchange

    $('.change').click(function (){
    var img1 = 'assets/img/arrow_right.png';
    var img2 = 'assets/img/arrow_down.png';
    var index = $(this).attr('index');
    var element = $('img[index='+index+']');
    if(element.attr('src') === img1){
    element.attr('src',img2);
    }else if(element.attr('src') === img2){
    element.attr('src',img1);

     }
    });

1 answer

0


Happens by the '.change' selector the event is being fired twice, when you click on the image it changes to the down arrow and in the sequence returns to the right... Change your selector to 'h1.change'.

$('h1.change').on('click', function() {
  var img1 = 'https://www.thetactilegroup.com/images/arrow_right.png';
  var img2 = 'https://www.thetactilegroup.com/images/arrow_down.svg';
  var index = $(this).attr('index');
  var element = $('img[index=' + index + ']');
  if (element.attr('src') === img1) {
    element.attr('src', img2);
  } else if (element.attr('src') === img2) {
    element.attr('src', img1);

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 index="1" class="collapsed change" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo" ng-click="alert_step2()">
  <img index="1" class="change img-change" src="https://www.thetactilegroup.com/images/arrow_right.png" style="width: 30px; height: 30px">Step 2 - Acknowledge Your Strengths (highest scores)
</h1>

  • I do not believe that the answer was so simple... Thank you so much for the help! I still need to study more JS!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.