Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of CSS style using jQuery

Tags:

jquery

css

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> 

I'd like to know if this method is correct because it is not working in my end. Thanks in advance for the little help.

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

like image 695
iMarkDesigns Avatar asked Sep 05 '12 01:09

iMarkDesigns


People also ask

What is the use of CSS () method in jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.

Can we change CSS property value using JavaScript or jQuery?

You can change CSS using the jQuery css() method which is used for the purpose of getting or setting style properties of an element. Using this method you can apply multiple styles to an HTML all at once by manipulating CSS style properties.

How do I get CSS?

There are three methods of including CSS in an HTML document: Inline styles — Using the style attribute in the HTML start tag. Embedded styles — Using the <style> element in the head section of a document. External style sheets — Using the <link> element, pointing to an external CSS file.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


2 Answers

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/

like image 73
wirey00 Avatar answered Sep 21 '22 12:09

wirey00


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

<script>   var n = $(".items").css("left");   if(n == -900){     $(".items span").fadeOut("slow");   } </script> 
like image 34
Hammad Khan Avatar answered Sep 22 '22 12:09

Hammad Khan