Make backgroundimage clickable in a CSS grid

Tags: , , ,



I have a div tag with a background image. How is it possible to make that div tag into a hyperlink on larger and smaller screens? Is it something like this?: onclick='window.location.href="https://www.google.com"'.

HTML:

<div class="sbp-item6"></div>

CSS:

.sbp-item10 {
    grid-row: 6 / 7;
    grid-column: 1/5;
    height: 250px;
    background-image: url("https://placehold.it/380x250");
}

Answer

If you use jQuery:

$( ".sbp-item6" ).click(function() {
     window.location.href = "https://www.google.com";
});

I think that if you have different divs that need to point to different urls, the better solution is to set an attribute to the div to be the url. Retreive it in js. And use it to point to the url itself.

<div class="sbp-item6" link-to="http://www.google.com"></div>
$( ".sbp-item6" ).click(function() {
    var url = $(this).attr("link-to");
    window.location.href = url;
});

And at the end, in css:

.sbp-item6
{
    cursor: pointer;
}


Source: stackoverflow