mathiasF
mathiasF

Reputation: 267

Change image dynamically with javascript

I'm looking to display images dynamically and according to their category. I have 4 buttons with the 1st I would like to display all the images and the 3 others I would like to sort them according to their categories. To know that an image can be in several categories.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
<body>
  <div class="link">
    <a onclick="showImg()" class="link__color">All</a><!--category: 0-->
    <a onclick="showImg()" class="link__color">category-1</a>
    <a onclick="showImg()" class="link__color">category-2</a>
    <a onclick="showImg()" class="link__color">category-3</a>
  </div>

  <div class="container">
    <!-- <div class="container__img"><img class="img" src=""></div> -->
  </div>

</body>
</html>

JS:

    const partners = [
  {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP267XEMpkNGK6SFQ97S0H417cdi3wwu6PtweMTOGSPreaJqFJWQ'`, category: [0,1,3]},
  {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR8YvxkmxhzlS3EQ9nmwODbfDvxzdYZZCbBl_Q3mkw53qH8QIv0hQ'`, category: [0,2]},
  {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGV9LR9tr0hSWJdUcD15OSk7p3X47sy4QFBB6SLOQXQYt7G8AnfA'`, category: [0,1,2]},
  {img: `src='https://c1.staticflickr.com/4/3823/11294769684_5d4b0d1a23_n.jpg'`, category: [0,1,2]},
  {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'`, category: [0,2,3]},
  {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'`, category: [0,2]},
  {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUgwZXDhsiXxNBQ8KAxFvVcOGU0mMd8gohhRf5OP4z0NOjeO6N'`, category: [0,3]},
];


function showImg(category) {
  const createDiv = document.createElement('div').setAttribute('class', 'container__img');
  /* creatDiv = is the div that will surround every img */
  partners.forEach(function() {
    if() {

    }
  });
}

That's where I am after trying a lot of things. So I would like to have each image put it in my class: container__img. And I'm not sure that forEach () is the right idea. (Plunker: https://plnkr.co/edit/OqCFuDExAbae8KDkfAhI?p=preview)

think it's not very complicated but for the moment I can't think of any ideas.

Upvotes: 1

Views: 1344

Answers (5)

scagood
scagood

Reputation: 782

Here is my take on what I think you mean:

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
</head>

<body>
    <div class="link">
        <a onclick="showImg(0)" class="link__color">All</a>
        <!-- Or:
        <a onclick="showImg([1,2,3])" class="link__color">All</a>
        -->
        <a onclick="showImg(1)" class="link__color">category-1</a>
        <a onclick="showImg(2)" class="link__color">category-2</a>
        <a onclick="showImg(3)" class="link__color">category-3</a>

        <!-- An additional example -->
        <a onclick="showImg([1,3])" class="link__color">category-1&3</a>
    </div>

    <div class="container"></div>
</body>

</html>
.link__color {
    margin: 10px;
    cursor: pointer;
    font-size: 24px;
}

.container {
    display: flex;
    flex-wrap: wrap;
}

.container .container__img {
    margin: 15px;
    width: 200px;
    height: 130px;
    background-color: red;
}

.img {
    width: 200px;
    height: 150px;
}
const partners = [
    {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP267XEMpkNGK6SFQ97S0H417cdi3wwu6PtweMTOGSPreaJqFJWQ'`, category: [0,1,3]},
    {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR8YvxkmxhzlS3EQ9nmwODbfDvxzdYZZCbBl_Q3mkw53qH8QIv0hQ'`, category: [0,2]},
    {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGV9LR9tr0hSWJdUcD15OSk7p3X47sy4QFBB6SLOQXQYt7G8AnfA'`, category: [0,1,2]},
    {img: `src='https://c1.staticflickr.com/4/3823/11294769684_5d4b0d1a23_n.jpg'`, category: [0,1,2]},
    {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'`, category: [0,2,3]},
    {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'`, category: [0,2]},
    {img: `src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUgwZXDhsiXxNBQ8KAxFvVcOGU0mMd8gohhRf5OP4z0NOjeO6N'`, category: [0,3]},
];

function showImg(category) {
    category = typeof category === 'number' ? [category] : category
    const container = document.querySelector(".container");

    container.innerHTML = "";

    partners.forEach(image => {
        // This will compare the requested categories with the images categories
        // E.g.
        // searching for: [2]
        // image categories: [0,2,3]
        // output: [2]

        // Then check the length to see whether we can show the image
        if (image.category.filter(e => ~category.indexOf(e)).length) {
            // Image is in categories

            // Create the elements
            const div = document.createElement('div');
            const img = document.createElement('img');

            // Add the classes
            div.className = 'container__img';
            img.className = 'img';

            // add the image source
            img.src = image.img.replace(/src='([^']+)'/, "$1");

            // Append to the correct locations.
            div.appendChild(img);
            container.appendChild(div);
        }
    });
}

Upvotes: 1

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23409

  1. Your probably want to remove the src= parts from (the original version of) your partners object.
  2. Your links need an href attribute or they won't look like links, they also need to return false or prevent default, they also need to include the category in the parameters..
  3. Filter the array with the filter method.
  4. Create and append each image to the container.

const partners = [
  {img: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP267XEMpkNGK6SFQ97S0H417cdi3wwu6PtweMTOGSPreaJqFJWQ", category: [0,1,3]},
  {img: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR8YvxkmxhzlS3EQ9nmwODbfDvxzdYZZCbBl_Q3mkw53qH8QIv0hQ", category: [0,2]},
  {img: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGV9LR9tr0hSWJdUcD15OSk7p3X47sy4QFBB6SLOQXQYt7G8AnfA", category: [0,1,2]},
  {img: "https://c1.staticflickr.com/4/3823/11294769684_5d4b0d1a23_n.jpg", category: [0,1,2]},
  {img: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27", category: [0,2,3]},
  {img: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27", category: [0,2]},
  {img: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUgwZXDhsiXxNBQ8KAxFvVcOGU0mMd8gohhRf5OP4z0NOjeO6N", category: [0,3]},
];


function showImg(category) {
  const container = document.querySelector(".container");
  container.innerHTML = "";
  const filteredImages = partners.filter(itm => ~itm.category.indexOf(category));
  filteredImages.forEach(itm => {
    const createDiv = document.createElement('div');
    createDiv.setAttribute('class', 'container__img');
    var img = new Image();
    img.onload = function() {
      createDiv.appendChild(img);
      container.appendChild(createDiv);
    };
    img.src = itm.img
  });
  return false;
}
.container__img{
  display: inline-block;
  width: 100px;
}

.container__img img{
  max-width: 100%;
}
<div class="link">
  <a href=# onclick="showImg(0)" class="link__color">All</a>
  <!--category: 0-->
  <a href=# onclick="showImg(1)" class="link__color">category-1</a>
  <a href=# onclick="showImg(2)" class="link__color">category-2</a>
  <a href=# onclick="showImg(3)" class="link__color">category-3</a>
</div>

<div class="container">
  <!-- <div class="container__img"><img class="img" src=""></div> -->
</div>

Upvotes: 3

Nianyi Wang
Nianyi Wang

Reputation: 773

Something like this:

<div id="src">
    <a data-category="0">category-0</a>
    <a data-category="1">category-1</a>
    <a data-category="2">category-2</a>
    <a data-category="3">category-3</a>
</div>
<div id="container"></div>
<script>{
    const images = [
        {
            src: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP267XEMpkNGK6SFQ97S0H417cdi3wwu6PtweMTOGSPreaJqFJWQ',
            category: [0, 1, 3]
        },
        {
            src: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR8YvxkmxhzlS3EQ9nmwODbfDvxzdYZZCbBl_Q3mkw53qH8QIv0hQ',
            category: [0, 2]
        },
    ],
    container = document.getElementById('container'),
    GenerateImg = src => {
        let img = new Image();
        img.src = src;
        return img;
    };
    document.getElementById('src').addEventListener(
        'click',
        e => {
            container.innerHTML = '';
            (
                category => images.filter(image => image.category.indexOf(category) !== -1).map(image => GenerateImg(image.src))
            )(+e.target.dataset.category).reduce((placeholder, current) => container.appendChild(current), void 0);
        }
    );
}</script>

Upvotes: 1

Chris Lear
Chris Lear

Reputation: 6742

Here's my version (no jquery). I've tried to stick as closely to the original code design as possible.

HTML

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
  </head>
<body>
  <div class="link">
    <a onclick="showImg(0)" class="link__color">All</a><!--category: 0-->
    <a onclick="showImg(1)" class="link__color">category-1</a>
    <a onclick="showImg(2)" class="link__color">category-2</a>
    <a onclick="showImg(3)" class="link__color">category-3</a>
  </div>

  <div class="container">
      <div class="container__img" id='container_img'><img class="img" src=""></div>
  </div>

</body>
</html>

JS

var partners = [
{img: "src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP267XEMpkNGK6SFQ97S0H417cdi3wwu6PtweMTOGSPreaJqFJWQ'", category: [0,1,3]},
{img: "src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR8YvxkmxhzlS3EQ9nmwODbfDvxzdYZZCbBl_Q3mkw53qH8QIv0hQ'", category: [0,2]},
{img: "src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGV9LR9tr0hSWJdUcD15OSk7p3X47sy4QFBB6SLOQXQYt7G8AnfA'", category: [0,1,2]},
{img: "src='https://c1.staticflickr.com/4/3823/11294769684_5d4b0d1a23_n.jpg'", category: [0,1,2]},
{img: "src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'", category: [0,2,3]},
{img: "src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27'", category: [0,2]},
{img: "src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUgwZXDhsiXxNBQ8KAxFvVcOGU0mMd8gohhRf5OP4z0NOjeO6N'", category: [0,3]},
];


function showImg(category) {
    var createDiv = document.createElement('div').setAttribute('class', 'container__img');
    /* creatDiv = is the div that will surround every img */
    createDiv = document.getElementById('container_img');
    createDiv.innerHTML = '';
    partners.forEach(function(partner) {
        if(partner.category.indexOf(category)!=-1) {
            createDiv.innerHTML = createDiv.innerHTML + '<img ' + partner.img + '>';
        }
    });
}

Upvotes: 1

Alen.Toma
Alen.Toma

Reputation: 4870

Here is a try, dont know if i understod you 100%

const partners = [
  {img: src ="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP267XEMpkNGK6SFQ97S0H417cdi3wwu6PtweMTOGSPreaJqFJWQ", category: [0,1,3]},
  {img: src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR8YvxkmxhzlS3EQ9nmwODbfDvxzdYZZCbBl_Q3mkw53qH8QIv0hQ", category: [0,2]},
  {img: src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQGV9LR9tr0hSWJdUcD15OSk7p3X47sy4QFBB6SLOQXQYt7G8AnfA", category: [0,1,2]},
  {img: src="https://c1.staticflickr.com/4/3823/11294769684_5d4b0d1a23_n.jpg", category: [0,1,2]},
  {img: src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27", category: [0,2,3]},
  {img: src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnccHtrN6iwkll-kIreBtv9jTM831XY2-wRvtevpb8ApCtdC27", category: [0,2]},
  {img: src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUgwZXDhsiXxNBQ8KAxFvVcOGU0mMd8gohhRf5OP4z0NOjeO6N", category: [0,3]},
];

function showImg(category) {
  const createDiv = $("#container")
  /* creatDiv = is the div that will surround every img */
  var index = $(category).index();
   $(createDiv).html(""); // clear data.
  $(partners).each(function(){
    if (this.category.find(function(v) { return v== index}) != undefined)
      $(createDiv).append($("<img style='width:50px' src='"+this.img+"' />"));
  
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">
    <a onclick="showImg(this)" class="link__color">All</a><!--category: 0-->
    <a onclick="showImg(this)" class="link__color">category-1</a>
    <a onclick="showImg(this)" class="link__color">category-2</a>
    <a onclick="showImg(this)" class="link__color">category-3</a>
  </div>

  <div id='container' class="container">
    <!-- <div class="container__img"><img class="img" src=""></div> -->
  </div>

Upvotes: 2

Related Questions