How to change the value of a custom attribute?

Asked

Viewed 61 times

1

I want to change the value of a custom attr via jquery, but without success. Follow 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 you click on a selector it changes the image that was set via data-image plus all this via jquery.

I have tried countless more unsuccessful options so far... someone can give me a light?

Thank you very much!

1 answer

2

Your code should work correctly, so if you give a console.log right after the attribute change will notice that the value has been 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 so $("#img-screen").data("image","img/bauru-02.jpg");

But I’m suspecting that 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 should rotate again the plugin/script that depends on the data-image value to work with.

Browser other questions tagged

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