E
E
Eric Grizzzzlie2018-03-21 16:54:23
css
Eric Grizzzzlie, 2018-03-21 16:54:23

How to write 1 function for 4 pictures?

There are 4 photos that, when clicked, should change and the words, when clicked, return the first (or the next and then the first again), I wrote the function, but when you click on 2 3 4, only the first picture changes.
I know that creating 4 functions is stupidity.

<a href="#"><img   id="image" onclick="changeImage()" src="img/like.png"></a>

function changeImage() {
  var image = document.getElementById('image');

  if(image.src.match("img/like.png")) {
    image.src = "img/like-full.png";
  }
  else {
    image.src = "img/like.png";
  }
}

and so on 4 pictures.
How to do it right?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
Igor, 2018-03-21
@TAPAKAHATOP

<a href="#"><img   id="image" onclick="changeImage(this)" src="img/like.png"></a>

function changeImage(elem) {...
Then you work with elem

D
Dmitry, 2018-03-21
@demon416nds

Pass a unique id for each image to the function or use the class

A
Anatoly Medvedev, 2018-03-21
@balamyt92

Something like this, maybe somewhere I made a mistake, did not check.

<img class="image"  src="img/like.png">
<img class="image"  src="img/like.png">
<img class="image"  src="img/like.png">
<img class="image"  src="img/like.png">

var images = document.querySelectorAll('.image');
images.forEach(function(image) {
  image.addEventListener('click', function(e) {
   if(e.target.src.match("img/like.png")) {
    e.target.src = "img/like-full.png";
  }
  else {
    e.target.src = "img/like.png";
  }
 })
})

E
Exploding, 2018-03-21
@Exploding

I thought, and here it is, the simplest, it’s probably nowhere easier already, I came up with a circular slider. Can it be simplified somehow? Huh, I can't do it anymore

<style>
      .one-line-slider > img{
        max-width: 320px;
        height: auto;
        display:none;
      }
      
      .one-line-slider > img:first-child{
        display:block;
      }
    </style>
    <script>
      $(document).ready(function(){
  
        $(".one-line-slider img").on("click", function(e){
          $(this).hide().next("img").show();
        });		
        $(".one-line-slider img:last").on("click", function(e){
          $(this).hide().siblings("img:first").show();
        });			
      });
    </script>
    <div class="one-line-slider">
      <img src='slides/1.jpg'>
      <img src='slides/2.jpg'>
      <img src='slides/3.jpg'>
      <img src='slides/4.jpg'>
    </div>

UPD: figured out how to simplify js
$(".one-line-slider img").on("click", function(e){
    if($(this).index() == $(".one-line-slider img").length-1)
      $(this).hide().siblings("img:first").show();
    else
      $(this).hide().next("img").show();
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question