How to change CSS property on click in jQuery?

The jQuery css() method can add CSS property to any of the element on the web page. This method also can change the existence CSS property of an element that is already set the CSS code. That means, if an element background color is black, you can change it to red. Or you can change the text color of an element also even if it is set from the CSS code also.

Live email validation using jQuery

Simply jQuery can replace any CSS property that is already given through CSS. The syntax of jQuery CSS method is given below:

$(selector).css(property)

Example: If we want to make the color of the paragraph tag <p> into blue then we can use the below JavaScript code with jQuery plugin:

$('p').css('color','blue');

 



Now we are going to change the CSS property of a div element using the css() method. For this, let’s take an HTML content:

<button>Change paragraph color</button>
<p>This is dummy text for testing our code.</p>

Now below is the CSS code for making the text color red that is inside the paragraph tag:

p { color: red; }

After the CSS code, we can see above, the text inside the <p> tag will be red.

Now suppose we want to change the color of the paragraph tag green when we click the button. To do it we use the jQuery css() method inside the jQuery click() method to apply the JavaScript onclick event listener.

Upload File With Ajax Using PHP and jQuery

Below is our jQuery code that will change the color of the paragraph tag into green:

$("button").click(function(){
    $('p').css('color','green');
});

That’s it. Now if we click the button, it will change the color of the paragraph text into the green. Just like CSS, in jQuery CSS method also we can use both color name and color code.

 

Leave a Reply

Your email address will not be published. Required fields are marked *