0

I want to add this..

data-0="background-position:0px 0px;" data-500="background-position:0px -250px;"

..to a div called 'section-1'. This is my code called within my document ready function, but it doesnt seem to work:

if($(window).width() > 767){
  $('#section-1').attr('0', 'background-position:0px 0px;');
  $('#section-1').attr('500', 'background-position:0px -250px;');
}

My css looks like this

#section-1{
  background-image:url(test.jpg); width:100%; height:500px;
}
@media only screen and (min-width: 767px){
  #section-1{
    background-image:url(test.jpg); background-size:100%; height:500px;
  }
}

It's for some parallax in case anyone was wondering.

Sultenhest
  • 49
  • 8
  • Be aware, you should use `window.matchMedia` not `window.width()` to completly fit with CSS media queries: https://developer.mozilla.org/en/docs/Web/API/Window.matchMedia – A. Wolff Feb 12 '15 at 10:42

2 Answers2

4

Your attribute is called data-0 so give the complete attribute name

$('#section-1').attr('data-0', 'background-position:0px 0px;');
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I see that works, but only when i use the Firebug, not when i try to view to source, and it doesn't parallax? Any idea why that is? – Sultenhest Feb 12 '15 at 10:46
  • 1
    @Sultenhest: Use a tool like the Chrome F12 DOM inspector as View Source tends to show the original server HTML file *before* any code is run on the page :) – iCollect.it Ltd Feb 12 '15 at 10:58
2

when you use the .attr function you have to put the "data" prefix too.

if you would use the .data function you can write it as you did

so:

$('#section-1').attr('data-0', 'background-position:0px 0px;');

or

$('#section-1').data('0', 'background-position:0px 0px;');

greetings timotheus

Timotheus0106
  • 1,536
  • 3
  • 18
  • 28
  • 3
    Your second option is incorrect. It will not store data as an attribute *(only read it from an attribute)*. Data will store it in a browser lookup dictionary behind the scenes. – iCollect.it Ltd Feb 12 '15 at 10:41
  • it seems to be working for me and others? http://stackoverflow.com/q/7163234/2645202 – Timotheus0106 Feb 12 '15 at 10:49
  • You are referencing irrelevant answers. `data()` *will not* change the *attribute* `data-` value in the HTML. – iCollect.it Ltd Feb 12 '15 at 10:50
  • You should have stopped at "thanks for this info" :P Just delete the incorrect second option and remove all reference to `.data()` to make it a correct answer. Consider yourself fortunate to get 2 upvotes from the ignorant masses. – iCollect.it Ltd Feb 12 '15 at 11:11