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

7
  • $(this).data('x') = "580"; is syntactically wrong.... $(this).attr("data-x", "580"); should work... how are you saying it is not working Commented Jun 4, 2015 at 5:15
  • If you are using data-api to access the value then need to use $(this).data("x", "580"); Commented Jun 4, 2015 at 5:15
  • stackoverflow.com/questions/14935191/… Commented Jun 4, 2015 at 5:17
  • api.jquery.com/data refer this Commented Jun 4, 2015 at 5:19
  • Probably, your DOM is not loaded at the moment of your script execution. Use jQuery document ready or window.onload functions. Commented Jun 4, 2015 at 5:22

2 Answers 2

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");
  });
})
Sign up to request clarification or add additional context in comments.

6 Comments

<script> $('#ctup-ads-widget-2').click(function(){ $(this).data("x","580"); }); </script>
@Melvin Screenshot is fine but you need to tell us which line you are getting that error.
@Melvin Have you included jQuery?
<script src="<?php bloginfo('template_url'); ?>/js/jquery.min.js"></script> <script type="text/javascript" src="ajax.googleapis.com/ajax/libs/jquery/1.8.2/…>
included in footer .. i have added the script to header .. is that be a pblm?
|
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.