Pedro Pedro - 4 months ago 14
HTML Question

How to swap an image

Is there a way to swap an image when the user click on link to expand the contnet on it.

<ul class="accor">
<li> Item 1 <img src="../plus.png">
<p> Lorem ipsum dolor sit amet</p>
</li>
</ul>

$('.accor li').click(function() {
$(this).find('p').slideToggle('fast');
})

Answer

You can change value of src attribute of your image. Or you can show these images as a background. Then you can toggle these images by changing class.

You can change value of src attribute as follows;

$('img').attr('src', 'newImageUrl');

Otherwise, you can make them background-image as follows;

style;

.icon {
  display: inline-block;
}

.first-image {
  background: url('../plus.png');
  width: 20px;
  height: 20px;
}

.second-image {
  background: url('../image-2.png');
  width: 20px;
  height: 20px;
}

By the way; you need to update height and width values of these classes by your images.

html;

<ul class="accor">
    <li> Item 1 <span class="icon first-image"></span>
      <p> Lorem ipsum dolor sit amet</p>
    </li>
</ul>

With last solution, you need to change class with javascript;

$('.accor li').click(function() { 
  var $icon = $(this).find('.icon');

  if ($icon.hasClass('first-image') {
    $icon.removeClass('first-image').addClass('second-image');
  } else {
    $icon.removeClass('second-image').addClass('first-image');
  }

  $(this).find('p').slideToggle('fast');
});

I hope this works.