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')
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.
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.
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.
CSS variables have access to the DOM, which means that you can change them with JavaScript.
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" />
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With