Place images in a div with jquery

Asked

Viewed 1,463 times

6

How can I place certain images in a div using jquery by clicking the button?

Follows the html:

         <div>
            <button id="btn2015" class="btn">2015</button>
            <button id="btn2014" class="btn">2014</button>
            <button id="btn2013" class="btn">2013</button>
            <button id="btn2012" class="btn">2012</button>
        </div>
        <div id="conteudo">

        </div>

Depending on each button clicked, the contents div will be emptied and the images will be placed according to the button. Follow the names of the images:

imagem_piscina_2015.jpg
imagem_sala_2015.jpg
imagem_escrito_2015.jpg

Besides these, there are several others with the same names, only the years ending with the different years. How can I make each button, call only the images according to their respective years?

  • What have you ever tried to do?

  • i made a click event for each button. The first thing I did was to empty the contents div. Later I tried to get the name of the image that is in the same file directory, but without success. :(

  • One image per button or 3 images per button?

  • use date attribute on buttons and put the URL of your SITE, something like: <button id="btn2015" class="btn" data-img="/imgs/imagem_piscina_2015.jpg">2015</button>, so in the event click, you read the attribute and an append in the div#conteudo, or already leaves an image there (with display:None), and changes src with jquery ($("img").attr("src",link_img) and has an effect on it to appear, with fadeIn(x) where x is the time in MS.

  • 1

    in this case 3, but I’m trying to do it in a way that takes the word ending, if you click on the 2015 button, the images that end in 2015 appear, if it’s the 2014 button, the images that end in 2014 and so on

3 answers

5

Here’s a suggestion:

var imagens = ['imagem_piscina_2015.jpg',
    'imagem_sala_2015.jpg',
    'imagem_escrito_2015.jpg'];

function criarImagem(nr) {
    return imagens.map(function (src) {
        var img = document.createElement('img');
        img.src = src.split('2015').join(nr);
        return img;
    });
}
$('button').on('click', function () {
    var ano = this.id.slice(3);
    $('#conteudo').html(criarImagem(ano));
});

jsFiddle: http://jsfiddle.net/2uasu6r9/

This code causes each time a button is pressed to be extracted the year and passed to a function. This function creates images (so many urls/names are given) and then inserts them into the div #conteudo, re-writing your content.

I suggest you adapt $('button') to be more accurate in the selector and also put the correct url in the images to point to the right place. In this array or within the function, via a configuration variable.

  • I just don’t understand what you did on that line var ano = this.id.slice(3);

  • @Diegodesouzasilva the idea is only to use the year in the string btn2015. With Slice I produce a new string that starts after the first 3 letters. The this is the button clicked and the id is the ID of that button.

2

I suggest you create an array, where the indices will be the years, and the values your respective images, something like:

arr['2015'] = "imgs/img_de_2015, imgs/img2_de_2015";

arr['2016'] = "imgs/img_de_2016, imgs/img2_de_2016";

and in the event button click, you get the year in which it refers(this you can put in the date-year attribute for example).

<button class="btn_ano" data-ano="2015">2015</button> $("button.btn_ano").click(function(){ ano = $(this).attr('data-ano'); imgs_arr = arr[ano].split(","); });

And right after that, make a loop to put the images in the view, like:

$(imgs_arr).each(function(i){ $("div#conteudo").append("<img src='"+imgs_arr[i]+"'/>"); });

Of course, if it gets slow(too many images), you can move on to a variable, and only then append to div#conteudo.

Something like:

imgs_html = ""; $(imgs_arr).each(function(i){ imgs_html.= "<img src='"+imgs_arr[i]+"'/>"; }); $("div#conteudo").append(imgs_html);

I hope I’ve helped!

2


One too many alternative to your case is:

@Edit: Following some suggestions, indicated by the friend @Sergio, considerable improvement in the code, follows changed

var imagens = {
  2015: ['http://www.sulandes.com.br/painel/arquivos/categorias/7cbcd56e187b498d6dd7603cd8250b24.png', 'http://4.bp.blogspot.com/-0FEJMBAc71c/VJbkENOA6qI/AAAAAAAAD2I/uYQiy_Xo5Us/s1600/2015-feliz%2Bano%2Bnovo-16.png'],
  2014: ['http://www.asacd.org.br/images/2014-calendrier.jpg', 'http://www.rio2016.com/sites/default/files/imagecache/switcher_710x450_rounded_corners/2014-foto_0.jpg'],
  2013: ['http://aclumontana.org/wp-content/uploads/2014/01/2013.jpg', 'http://www.jornalistasconcurseiros.com.br/blog/wp-content/uploads/2013/01/2013.jpg']
};

document.addEventListener('click', function(e) {
  var id = e.target.id;
  if(['2015', '2014', '2013'].indexOf(id) !== -1) {
    var conteudo = document.getElementById('conteudo');
    conteudo.innerHTML = '';
    Array.prototype.forEach.call(imagens[id], function(arr) {
      var img = document.createElement('img');
      img.src = arr;
      conteudo.appendChild(img);
    });
    console.log(conteudo);
  }
});
div img {
    width: 100px;
}
<button id="2015">2015</button>
<button id="2014">2014</button>
<button id="2013">2013</button>
<div id="conteudo"></div>

In this code an object has been declared images containing attributes with year name and value containing an array with image url. It has also been declared an Event Listener to detect click events referring to buttons, this event calls a function that checks the year, clears the previous content and traversing the array, creates elements <img> assigning the url to your src.

See working here on jsfiddle

  • 1

    Just suggestion, I think the code could be clearer like this: https://jsfiddle.net/go221ezy/

  • @Sergio really, the id validation you used for sure is more "clean", I will change my code based on your suggestion, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.