1

My html is

<div id="ctup-ads-widget-2" class="caption slide-heading "  data-x="380" data-y="80" data-speed="1800" data-start="1200" data-easing="easeOutExpo">Hui</div>

I am trying to change the values of dat=x and data-y dynamically

I tried both below which did not work.

<script>
$('#ctup-ads-widget-2').click(function() {

    $(this).attr("data-x", "580");
});
</script>

and

<script>
$('#ctup-ads-widget-2').click(function() {
    $(this).data('x') = "580";
});
</script>

and

<script>
window.onload = function() {
    var anchors = document.getElementById('ctup-ads-widget-2');
    for (var i = 0; i < anchors.length; i++) {
        anchors[i].setAttribute('data-x', '580');
        anchors[i].setAttribute('data-y', '30');
    }
}
</script>

console screenshot

enter image description here

error screenshot

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
Melvin
  • 383
  • 1
  • 13
  • 40

2 Answers2

3

You can't use it like

$(this).data('x') = "580";//won't work

Try with data()

 $(this).data("x","580"); //$(this).attr("data-x", "580") should also work

Update

Enclose it in $(document).ready..

$(document).ready(function(){
  $('#ctup-ads-widget-2').click(function() {
    $(this).data("x","580");
  });
})
Zee
  • 8,420
  • 5
  • 36
  • 58
0

If data-attribute needs to be dynamically added on an element,

$("this").attr("data-x", "5");

can be used.

From seeing your screenshots, it's clear that jQuery was not loaded properly. Use <script> tag to load jQuery file before end of </body> tag.

Example:

<body>
...
..
<script src="js/jQuery.js"></script>
<script src="js/yourfile.js"></script>
</body>
avk87
  • 1
  • 1
  • 4