Question

I have the following jQuery code :

This is the HTML :

<div 
    class="continueReading" 
    data-skip="0" 
    data-categories="22,243" 
    data-is="single" 
    data-s="cd1f2f7a7d" 
    data-list="latestNews-sidebar-1"
>
    <a href="javascript:void();" class="latestNewsWidgetMoreLink">get more</a>
    <a href="javascript:void();" class="latestNewsWidgetMoreButton">»</a>
</div>

and jQuery is this :

$('.latestNewsWidgetMoreLink, .latestNewsWidgetMoreButton').click(
    function()
    {    
        total_items = 10;
        $(this).parent('div').attr('data-skip', total_items);
    }
);

but seems don't work. Can somebody to help me? Is there any error in this code ?

Note : I have also try the following code with no luck:

total_items = 10;
$(this).parent('div').data('skip', total_items);
Was it helpful?

Solution

The code works for me in this example jsFiddle. I suspect the code is executing too early, and as a result the click event handlers aren't being bound to the elements (because they don't exist yet). Try wrapping it in a $(document).ready() call:

$(document).ready(function () {
    $('.latestNewsWidgetMoreLink, .latestNewsWidgetMoreButton').click(function () {
        total_items = 10;
        $(this).parent('div').data('skip', total_items);
    });
});

That will ensure the code doesn't execute until the DOM is ready, so the elements will exist and can have event handlers bound.

Note that I've made a couple of adjustments:

  1. Removed the semi-colons from the href attributes of the <a> elements - was causing a JavaScript syntax error
  2. Using the .data() jQuery function rather than .attr()

OTHER TIPS

Remove javascript:void(); from both link and then inspect HTML DIV with firebug and click on link , it will set data-skip="10";

The code works fine. See this. The second link won't work because you have forgot the dot in the jQuery selector. So you have to change

$('.latestNewsWidgetMoreLink, latestNewsWidgetMoreButton')

in

$('.latestNewsWidgetMoreLink, .latestNewsWidgetMoreButton')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top