Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery var and $(var).css

Tags:

jquery

dom

css

var

I have this code:

$(document).ready(function() {
  $('.fa-crosshairs').click(function() {
    $('*').click(function() {
      var currentclass = $(this).attr('class');
    });
  });
  $('#1color').click(function() {
    $('body').css({
      "background-color": "black"
    });
  });
});

I need to get currentclass var, then use it instead of $('body').css, but i dont know how i have to do it.

The point is to get one element by clicking, and then, change its css when i click on ('#1color')

like image 921
nanaki Avatar asked Dec 16 '14 13:12

nanaki


People also ask

Can we change CSS using 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.

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 you change CSS variables?

CSS variables can be made conditional with @media and other conditional rules. As with other properties, you can change the value of a CSS variable within a @media block or other conditional rules. For example, the following code changes the value of the variable, gutter on larger devices.

Can I use CSS variables in JavaScript?

CSS variables have access to the DOM, which means that you can change them with JavaScript.


2 Answers

Declare the variable globally.

Here's an example of how you could do this.

$(document).ready(function() {
  var elem;
  $('.fa-crosshairs').click(function() {
    elem = this;
  });
  $('input').click(function() {
    $( elem).css({
      "background-color": "teal",
      "color": "white"
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="fa-crosshairs">One</div>
<div class="fa-crosshairs">Two</div>
<div class="fa-crosshairs">Three</div>
<div class="fa-crosshairs">Four</div>
<div class="fa-crosshairs">Five</div>
<div class="fa-crosshairs">Six</div>
<input type="button" value="Change" />
like image 139
Weafs.py Avatar answered Oct 03 '22 06:10

Weafs.py


The variable var currentclass = $(this).attr('class'); is declared inside a function. so that it is accessible inside the function where it is declared. The scope of the variable is inside that function. You need to declare the variable as GLOBAL VARIABLE so that it is accessible outside the function. SCOPE OF A VARIABLE

like image 39
Karthik Avatar answered Oct 03 '22 05:10

Karthik