M
M
mt_max2018-02-17 00:47:56
css
mt_max, 2018-02-17 00:47:56

How to use the data attribute?

Hello, tell me, I want images to change in divs, and store the path to the image in the data attribute. I'm trying to do this:

<div id="f4" class="thumbnails-container" style="max-height: 350px; user-select: text;">
<div id="ap4_id6" class="instance-thumbnail" data-clastering="url(static/user/four-chamber-clastering/6.jpg)" 
style="width: 100px; height: 100px; background-image: url(static/user/four-chamber/6.jpg); 
user-select: text;"><span class="instance-no">6</span></div></div>

var divs = document.querySelectorAll(".thumbnails-container > div");
    var cont = document.getElementById("container-1-1");
    var cont2 = document.getElementById("container-2-1");
    for(var i = 0 ; i<divs.length; i++){
    divs[i].onclick = function(){
      cont.style.backgroundImage = this.style.backgroundImage;
      cont2.style.backgroundImage =this.data('clastering');
    }

    }

As a result, the picture changes in the cont block, but does not change in the cont2 block, please help me fix it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ernest Faizullin, 2018-02-17
@erniesto77

hint:

var divs = document.querySelectorAll(".thumbnails-container > div");

var cont = document.getElementById("container-1-1");
var cont2 = document.getElementById("container-2-1");

for (var i = 0 ; i < divs.length; i++) {

    divs[i].addEventListener('click', function(event) {
        var target = event.target;

        cont.style.backgroundImage = target.style.backgroundImage;
        cont2.style.backgroundImage = target.dataset.clastering;
    });

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question