Jacob Likecocain
Jacob Likecocain

Reputation: 103

Javascript image src change on click event

I am doing a image switcher, I was trying solutions applied there, but I can not help myself.

Very simple thing, I am trying to make a image switcher. Team members are changing after a click, and also class of the a member name from ""active-members-link" to the "members-link". Unfortunately I don't know why both doesn't work, please share your thoughts with me. I want to add more members in future so it can not be if statement.

Please vanilla Javascript.

    <script>
            function changeImage(img) {
            let image = document.getElementById("ChangePic");
            let currentAddres = document.getElementById("ChangePic").src;
            image.src = img.src.replace("$currentAddres", "{{$site_url}img/{$this.innerHTML.jpg}");

            let currentActive = document.getElementsByClass("active-members-link");
            currentActive.class = "members-links";
            this.class = "active-members-link";
            }
    </script>
    <section class="fp-section margin-div">
        <div class="fp-main-visual">
                <img class="fp-main-visual__image fp-main-visual__image--pc ofi" src="{$site_url}img/big3.jpg" width="300" height="300" alt="{$cl_dat.cl_name}">
                 <img class="fp-main-visual__image fp-main-visual__image--sp ofi" id="changePic" src="{$site_url}img/John John.jpg" width="300" height="300" alt="{$cl_dat.cl_name}">
        </div>
        <div class="container after-article mx-auto">
            <div class="row">
                <div class="col-12 col-lg-6 text-center"><a class="active-members-link" href="" onclick="changeImage(this)">John John</a></div>
                <div class="col-12 col-lg-6 text-center"><a class="members-links" href="" onclick="changeImage(this)">John2 John2</a></div>
            </div>
        </div>
    </section>

Thank you

Upvotes: 2

Views: 690

Answers (1)

zer00ne
zer00ne

Reputation: 43880

Use .querySelector() to reference elements. Below are three ways to reference an element:

<img id="ID" class="CLS">

TagName: document.querySelector('img');
id: document.querySelector('#ID');
className: document.querySelector('.CLS');

If you want to add more members then organize each one into an object literal:

{url: 'http://website.com/image.jpg', txt: 'Member Name'}

Then store all of them into an array:

const ArrayOfObjects = [{url:"*", txt:"*"}, {url:"*", txt:"*"}, ...]

Wrap an event listener in a function to create a closure so you can pass in parameters when a 'click' event happens.

Details are commented in example below

/* Define an array of objects
Each object has 2 properties:
  "url" for src property of the <img>
  "txt" for the text of <figcaption>
[ {url: *, txt: *}, {...}, {...}, ...]
*/
let data = [{
  url: 'https://styles.redditmedia.com/t5_3g6gs7/styles/profileIcon_6gz6l1b77jd61.jpg?width=256&height=256&crop=256:256,smart&s=36d1caa14aa1bf9f67a6c35fb1d588b31613459b',
  txt: 'Ninja Girl'
}, {
  url: 'https://steamuserimages-a.akamaihd.net/ugc/871873319171427467/DF62F343D27001BCD92704A77C6472FD5451E7BD/',
  txt: 'Azumi'
}, {
  url: 'https://store.playstation.com/store/api/chihiro/00_09_000/container/US/en/19/UP4312-CUSA02383_00-AV00000000000001/image?w=320&h=320&bg_color=000000&opacity=100&_version=00_09_000',
  txt: 'Sniper'
}];

// Reference the parent element of the <img> and <figcaption> (which is <figure>
const frame = document.querySelector('figure');

/* function passes:
  node: A reference to parent element
  image: A string of the image element by:
    tagName: "img"
    className: prefix with "."
    id: prefix with "#"
  caption: As above for the element that has the text
  objArray: The array of object
*/

function eventHandler(node, image, caption, objArray) {
  // Define the initial value of counter. The counter represents the current index of `objArray`
  let i = 0;
  // Register the parent element to the click event
  node.addEventListener('click', function(e) {
    // Reference the children of `node`
    const img = this.querySelector(image);
    const cap = this.querySelector(caption);
    // if the counter is less than the number of objects in `objArray -1`...
    if (i < objArray.length - 1) {
      //...increment the counter...
      i++;
      //Otherwise...
    } else {
      //...reset the counter
      i = 0;
    }
    // Set `img` src property to the current object [url] property
    img.src = objArray[i].url;
    // Set `cap` text of the current object [txt] property
    cap.textContent = objArray[i].txt;
  });
}

eventHandler(frame, 'img', 'figcaption', data);
figure {
  border: 3px inset grey;
  width: 150px;
  height: 150px;
  cursor: pointer;
}

img {
  width: 100%;
}

figcaption {
  font: 2ch/1 Consolas;
  text-align: center;
  padding: 3px 2px;
}
<figure>
  <img src="https://cdn0.iconfinder.com/data/icons/communication-line-10/24/account_profile_user_contact_person_avatar_placeholder-512.png">
  <figcaption>Click Image <br>or Text</figcaption>
</figure>

Upvotes: 4

Related Questions