Basic jQuery Tutorial: Change CSS

February 27, 2010 |  by Mukesh Chapagain

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,

Related Posts with Thumbnails

No Comments


Trackbacks

  1. Design Gala
  2. JQuery Watcher
  3. Basic jQuery Tutorial: Change CSS | Drakz Free Online Service
  4. WordPress Rocker
  5. WordPress Rocker

Leave a Reply