17
Jul
2012

jQuery close / delete button

Posted in: jQuery , No Comments

jquery_logo

In this jQuery tutorial I will show you how to create a simple delete / close button. When you click this button a selected div / region will close / disappear.

This is very useful when you want to show some message to your site visitors and also want to give him option to hide that message.

Step 1:
Create a message box with some text.

<div class="messagebox">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi malesuada, ante at feugiat tincidunt</div>

Step 2:
Add a close button to the above message box.

<div class="close"></div>

Step 3:
Add CSS for class messagebox and close

.messagebox {
padding: 10px;
border-radius: 5px;
background: #dddddd;
text-shadow: 1px 1px #fff;
color: #222;
border: 1px solid #b7b7b7;
}
.close{
background: url(img/close.png) no-repeat;
width: 48px;
height: 48px;
cursor: pointer;
float: right;
}

Step 4:
Call jQuery Library

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Step 5:
Now we will add jQuery code in head section and tell it to hide region of class messagebox when close button is clicked.

<script type="text/javascript">
$(document).ready(function(){
	$(".messagebox .close").click(function(){
	$(this).parents(".messagebox").animate({ opacity: "hide" }, "slow");
	});	
});
</script>

So, our final code is like:

<!DOCTYPE html>
<html>
<title>jQuery close or delete button</title>

<head>
<style type="text/css">
body {
margin: 0 auto;
padding: 0;
}
.messagebox {
padding: 10px;
border-radius: 5px;
background: #dddddd;
text-shadow: 1px 1px #fff;
color: #222;
border: 1px solid #b7b7b7;
}
.close{
background: url(img/close.png) no-repeat;
width: 48px;
height: 48px;
cursor: pointer;
float: right;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	$(".messagebox .close").click(function(){
	$(this).parents(".messagebox").animate({ opacity: "hide" }, "slow");
	});	
});
</script>
</head>
<body>
<div class="messagebox">
<div class="close"></div>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi malesuada
</div>
</body>
</html>

Done!!!
Check below link for live demo.

About the Author

Name: Ravi Shekhar
I love learning and sharing web stuffs.

Share this post

Twitter Facebook Google Buzz Digg StumbleUpon Delicious Technorati

Leave a Reply