How to make the background of a div clickable in HTML ?
Last Updated :
28 Dec, 2023
In web development, it is often desirable to make an entire area clickable, rather than just a hyperlink. One way to achieve this is by setting the background of an <div> element to a specific color or image and then making that background a clickable link.
To make the background of a ‘<div>’ clickable in HTML, you can use follow the steps:
- Ensure you have a `<div>` element in your HTML that you want to make clickable. Give it an `id` or `class` for identification.
- Use CSS to set the desired background for the <div>. You can use the `background` property to define the background color or image.
- Write a JavaScript function that should be triggered when the <div> is clicked. This function can be designed to navigate to a specific URL or perform any desired action.
- Use JavaScript to bind the click event to your `<div>`. This is typically done by selecting the `<div>` using its `id` or `class` and attaching an event listener for the “click” event.
Approach 1: Using an anchor tag
The first approach is to wrap the entire <div> element inside an anchor tag (<a>). This way, clicking anywhere inside the <div> will trigger the link.
Syntax:
<a href="yourLink">
<div>
<!-- Your content goes here -->
</div>
</a>
Example: In this example, we will use the anchor tag to make the background clickable.
HTML
<!DOCTYPE html>
< html >
< head >
< title >Clickable Background</ title >
< style type = "text/css" >
.box {
width: 200px;
height: 200px;
background-color: #666764;
cursor: pointer;
}
.box:hover {
background-color: #000000;
}
</ style >
</ head >
< body >
< h1 style = "color:green" >GeeksforGeeks</ h1 >
< a href =
< div class = "box" >
Click me!
</ div >
</ a >
</ body >
</ html >
|
Output:
Output
Approach 2: Using JavaScript
The second approach is to use JavaScript to capture the click event on the <div> element and redirect the user to the desired link.
Syntax:
<div onclick="location.href='yourLink';">
<!-- Your content goes here -->
</div>
Example: In this example, we will use the above approach.
HTML
<!DOCTYPE html>
< html >
< head >
< title >Clickable Background</ title >
< style type = "text/css" >
.box {
width: 300px;
height: 300px;
background-image: url(
cursor: pointer;
}
.box:hover {
opacity: 0.7;
}
</ style >
</ head >
< body >
< div class = "box"
onclick=
Click me!
</ div >
</ body >
</ html >
|
Output:
Output
Share your thoughts in the comments
Please Login to comment...