user1222728
user1222728

Reputation: 187

Custom CSS properties or HTML attributes?

I'm experimenting with parallax scrolling, and I want to do something like:

$('.page').each(function() {
    $(this).css("background-position", 
        "center " + ((window.pageYOffset - $(this).offset().top) /
                     $(this).css("speed")) + "px");
});

Where speed is an attribute assigned to the specific item that controls the movement speed of an item during scrolling. So I would have something like:

#item { speed: 4; }

and

<div name="item" class="page"></div>

I understand this might not be possible with CSS. HTML5 supports custom attributes, but I'd rather declare these things somewhere in the head with other information about the element.
Any recommendations on how to do this?

Thanks!

Upvotes: 1

Views: 597

Answers (2)

marue
marue

Reputation: 5726

You cannot do this with CSS. But you can use the HTML5 custom attributes, and if you want to declare everything in the header, as you said in your question, you could use jQuery's own method to bind data to elements:

$(document).ready( function(){
    $.data(selector,'speed',5);
    alert($.data(selector,'speed')); //this will alert 5 now
});

The docs are here: http://api.jquery.com/jQuery.data/

And this one should also work: http://api.jquery.com/data/ - code would look a bit different here:

$(document).ready( function(){
    $(selector).data('speed',5);
    alert($(selector).data('speed')); //this will alert 5 now
});

Hope thath helps.

Upvotes: 2

Geert
Geert

Reputation: 1824

HTML5 with custom data- attribute:

<div name="item" class="page" data-speed="4"></div>

Using jQuery’s data() method in your loop:

parseInt($(this).data('speed'), 10);

Upvotes: 1

Related Questions