1

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.

12
  • {img: src="..."}? Commented Feb 5, 2018 at 14:40
  • forEach is the preferred way to visit each element in an array. I would use filter, before the forEach, instead of the if, for readability reasons. .filter(image => image.category.includes(category)) .forEach(image => {...}) Commented Feb 5, 2018 at 14:44
  • @Iwrestledabearonce . I don't know how to add images in the js, I modified maybe it's better I don't know :( Commented Feb 5, 2018 at 14:49
  • @Aluan Haddad I can see a little bit of what you want to do. I'm gonna try Commented Feb 5, 2018 at 14:51
  • 1
    You can put the URLs in the DOM attributes as data-src, then visit them in JavaScript by element.dataset.src. Commented Feb 5, 2018 at 14:53

5 Answers 5

3
  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>

Sign up to request clarification or add additional context in comments.

5 Comments

In the all a tag is missing the 0 category, this should show all images
@Iwrestledabearonce I didn't know that sign (~). It took me a long time to understand what I know but it's really interesting :) . thanks
@mathiasF - it turns a -1 into a zero
I try to have the category all by default when I arrive on the page. I tried several solutions on the Internet but nothing works, I thought that adding return false to onclik was enough. But alas, it still doesn't work. If anyone has an idea?
@mathiasF ... add this to the bottom of your script... $(()=>showImg(0));
2

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>

1 Comment

WOW thanks you very much. However, I wish I didn't have to install jquery. I will try to find something similar in pure javascript. But thank you very much
1

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

6 Comments

Ah, I didn't think we could do it that way. Thank you, that's the perfect answer.
However I don't understand why the .container__img css doesn't apply. If they are dynamically created I have to add the css dynamically too? Or what should the css add to #container__img?
I'm not sure I understand this question. What css? It may be that you are confusing the name of the class (container__img) with the id of the div (container_img). The number of underscores is the difference.
In fact it's my fault I copied the code and I didn't see it but you didn't put the link to the js page. <script src="script.js"></script>
True. I didn't have that file, so I didn't include it.
|
1

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>

1 Comment

you can replace the GenerateImg method with any DOM structures you want, say, an <img> wrapped with a <div>.
1

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

6 Comments

Thank you very much for your answer, I didn't think about the regex too. That's very interesting. I'll try it on.
Adding onclick attributes on every <a> seems a little redundant... You can handle them using a forEach or catch them in a parent click event. (I prefer event because multiple event bindings is a waste of memoy...)
Here too I don't understand why the container css is not displayed
I was trying to keep my example as close to the provided code as possible, @NianyiWang
How do you mean @mathiasF? Here is a fork of your plunk: plnkr.co/edit/Jq8JfBO8kOhOoQBmPHKG?p=preview, the images seem to be wrapping to me?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.