How to change the value of a custom attribute?

1

I want to change the value of a custom attr via jquery, but without success. Here is the code below:

$("#botao-01").click(function() {
    $("#img-screen").attr("data-image","img/bauru-02.jpg");
 });
<div id="img-screen" class="tile" data-scale="2.4" data-image="img/bauru-01.jpg" alt="Equipamento 01"></div>

What I want is when I click on a selector it changes the image that was set via data-image plus all this via jquery.

I've tried countless more unsuccessful options so far ... can anyone give me a light?

Thank you!

    
asked by anonymous 03.04.2018 / 14:58

1 answer

2

Your code should work correctly, so that if you give a console.log shortly after changing the attribute you will notice that the value has changed in runtime .

$("#botao-01").click(function() {
    $("#img-screen").attr("data-image","img/bauru-02.jpg");
    console.log($("#img-screen").attr("data-image"));
 });
<div id="img-screen" class="tile" data-scale="2.4" data-image="img/bauru-01.jpg" alt="Equipamento 01"></div>

Another way to change is to do $("#img-screen").data("image","img/bauru-02.jpg");

But I suspect you have another script / plugin running on the page, something that uses the data-scale to transform your image. If so, whenever you change the data-image you must run again the plugin / script that depends on the data-image value to work.

    
03.04.2018 / 15:07