44

I'd like to know what type of method should I use to get the value of CSS style. I want to set it to jQuery so that I can create conditions to match on CSS "left" value.

Here is the CSS and HTML tag with the style attributes.

<div class="items" style="left: -900px"> <span>some content here</span> </div>

Here is my jQuery code to get the value.

<script>
  var n = $("items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

Is this method correct? It is not working in my end.

Note: left value was dynamic, and it was changing to these value: -900px, -1800px, -2700px, -3600px, -4500px...

1
  • Do u want the value of the attribute, OR the actual position? Commented Sep 5, 2012 at 1:57

3 Answers 3

47

I doubt css understands left by itself. You need to use it specifying position. You are using .css() correctly

position: relative/absolute/whatever;
left: 900px;

heres a fiddle of it working

https://jsfiddle.net/gFLZe/

and without the position here's what you get

https://jsfiddle.net/gkkm5/

Change your if statement to be like this - with quotes around -900px

var n = $("items").css("left");

if(n == '-900px'){
    $(".items span").fadeOut("slow");
}

https://jsfiddle.net/gFLZe/1/

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

1 Comment

Yes, actually the position itself are already coded at the plugin i am using.. although i have to customize the output to make each content have different visual.
4

You code is correct. replace items with .items as below

<script>
  var n = $(".items").css("left");
  if(n == -900){
    $(".items span").fadeOut("slow");
  }
</script>

Comments

0

Yes, you're right. With the css() method you can retrieve the desired css value stored in the DOM. You can read more about this at: https://api.jquery.com/css/

But if you want to get its position you can check offset() and position() methods to get it's position.

1 Comment

No. His mistake was writing "items", which is searching for the tag times, instead of writing ".items" which would capture the class items. All the difference lies in the dot.

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.