1

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!

1
  • Why Do you not use JavaScript for this Commented Apr 6, 2012 at 8:09

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

3 Comments

'I'd rather declare these things somewhere in the head' - That throws HTML5 out of the race. And using parseInt is absolutely unnecessary when using jQuery.
Just out of interest: why did you use parseInt here?
Just a good habit. You expect the data-speed attribute to be an integer, but you don't have to assume it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.