fotant fotant - 5 months ago 27
Javascript Question

Make body background image act as link

I've read many things online but I haven't found a way to make it work..

What I want:

I have a body background image and I was asked to make it a link as an advertisement.. The problem is that whatever I tried makes the whole page a link, whereas I want only the background of the webpage to act as a link. Is it possible,through html and css? Or even with use of javascript? Any solution is accepted... I'm stuck..Thanks in advance!

Answer

You can't have the background image be the link. You can use JS to catch all clicks that are on the body, but not on one of its children

// This is not cross browser, that would be a separate question
document.body.onclick = function(e) {
  if (e.target === document.body) {
      window.location = "link.html"
  }
}

You can use jQuery for a cross browser version

$('body').click(function(e){
    if (e.target === this) {
        window.location = "link.html"
    }
});

If you want to give the background the cursor appearance, you can apply the following CSS

body {
   background-image: url(http://www.blutest.com/sites/default/files/butterfly2_large_0.jpg);
   cursor: pointer;
}

body, html {
   width: 100%;
   height: 100%;
}

body * {
  cursor: default;
}
‚Äč

See it in action here