Basic jQuery Tutorial: Change CSS

Pin It


In this article, I will be showing you how to add or change css styling. You will be able to add or remove class in HTML elements.

VIEW DEMO

Here is my html code:

<div>
	<span>Sample text!</span>
	<br />
	Testing!
</div>
<br />
 
<div>Click me</div>

As you can see above, I have a div with id ‘content’. I have ‘Sample text!’ inside span. And I have a div with id ‘clickme’.

Here is CSS class to be used:

.hover {
	text-decoration: underline;
	cursor: pointer;
	color: #003399;
	font-weight: bold;
}

Here is the magical jQuery function :)

$("#clickme").hover(function(){
	$(this).addClass("hover");
}, function(){
	$(this).removeClass("hover");
});

Here, ‘hover’ function is used. It means that, when we hover on ‘Click me’ div then the CSS class ‘hover’ is added to the ‘clickme’ div. The ‘hover’ class will change the color, font-weight, etc. of the div text ‘Click me’.

Now, when we click the ‘Click me’ text, then the CSS styling is added to the div ‘content’. The new styling will change the text of div ‘content’ to green in color and it also increases the font size. The following jQuery code is used:

$("#clickme").click(function(){
	$("#content").css({"color":"green","font-size":"20px"});
});

VIEW DEMO

Cheers,

4 total comments on this postSubmit yours
  1. Hi,
    nice article i think changing css can be useful.

    Can i ask how did you get rid of the linkwithin text on the related topics section?

    Thanks
    Sam

  2. thanks for the tutorial but i still could change the label text to bold using $(‘label’).css(“font-weight”:”bold”);

  3. sorry i meant COULD NOT :

  4. Hi,

    Came across your site when looking for the above; I’m a bit of a jQuery noob, but noticed you made a mistake…

    In the post above it states…

    Sample text!

    Testing!

    Click me

    But you didn’t give the div an id of clickme

    i.e. it should have been:

    Sample text!

    Testing!

    Click me

    Thanks for this post nonetheless :)!!

6 total pingbacks on this post
Submit your comment

Please enter your name

Your name is required

Please enter a valid email address

An email address is required

Please enter your message

Twitter

  • May 2, 2012 04:15

    10 Free WordPress Theme To Make You Forget About Premium Theme http://t.co/YRiLCiVa

  • March 2, 2012 17:16

    3 Helpful Tools to Test Cross Browser Compatibility of Webpage http://t.co/FY0jh8Dn

  • March 2, 2012 16:43

    3 Helpful Tools to Test Cross Browser Compatibility of Webpage http://t.co/QUlYKInf #IE #FF #Chrome #Testing #CrossBrowser

  • March 2, 2012 12:52

    Top 5 Plugins to Build Contact Form for WordPress http://t.co/PWyR08Iq #WordPress #Plugins #ContactForm

  • June 11, 2011 02:49

    CSS 3 Transitions http://bit.ly/m0pK3t

Design Gala © 2012 All Rights Reserved

Designed by 76miles

Powered by WordPress

More in CSS, jQuery (9 of 32 articles)
jquery-logo