Pedro
Pedro

Reputation: 1450

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

Upvotes: 1

Views: 68

Answers (3)

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve your expected result, use below option

HTML:

<ul class="accor">
    <li> Item 1 <img src="http://www.w3schools.com/css/img_fjords.jpg">
      <img src="http://www.w3schools.com/css/img_forest.jpg" width="60px" height="60px" style="display:none"/>
      <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </li>
</ul>

CSS:

img{
  width:100px;
  height:100px
}

JS:

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

Codepen-http://codepen.io/nagasai/pen/kXvdyQ

Upvotes: 1

Ali BARIN
Ali BARIN

Reputation: 1920

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.

Upvotes: 2

Washington Guedes
Washington Guedes

Reputation: 4365

You can use just css:

img {
    opacity: 1;
}

img:hover {
    opacity: 0;
}

When the opacity is set to 0, the image became hidden, this way you can see the paragraph's text.

Upvotes: 2

Related Questions