-1

This question relates to the last i asked on this site - Using javascript to "link" from html background image?.

I received a good answer which worked, however the link for the background image is also applied to the container. How would I go about ensuring that only clicking on the background image (of the id body) and not the container links to whatever website?

I hope I have been clear enough. Many thanks in advance.

The html:

<html>

<head>
<link href = "style1.css" rel = "stylesheet" type = "text/css">
</head>

<div id = "header">
Header
</div>

<body>

<div id = "body">

<div class = "container">

</div>
</div>

</body>

</html>

<script>
document.getElementById('body').onclick = function() {
window.location = 'http://www.google.com/';
}
</script>

The CSS code:

#header{
width:100%;
height:50px;
background-color:black;
}

#body {
width:100%;
height:2000px;
background-image:url('uploads/1.jpg');
cursor:pointer;
}


.container{
 width: 1000px;
margin-right: auto;
margin-left: auto;
height: 1000px;
background-color:white;
}
5
  • 2
    JavaScript is not Java. Also, please post the code you have now. Commented Feb 5, 2013 at 15:44
  • Yeah, sorry. I will do.. Commented Feb 5, 2013 at 15:46
  • This doesn't warrant the need for a new question. You could of just asked this on the comments of the answer you accepted, as it's heavily related. Commented Feb 5, 2013 at 15:48
  • I see. I'm relatively new with this site. Commented Feb 5, 2013 at 15:49
  • You can't have a <div> outside of your <body> like that! Commented Feb 5, 2013 at 16:01

3 Answers 3

2

In your click handler, you can check the element that was clicked on, if it's not body (meaning it's a child), then don't do anything.

document.getElementById('body').onclick = function(e) {
    // e.target is what you clicked on
    // this is always what the event was bound to
    if(e.target === this){
        window.location = 'http://www.google.com/';
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

What browser are you using? It worked for me in IE 9 and Chrome 25.
0

Try add this code in your script:

document.querySelector('#body .container').onclick = function() {return false; }

To have:

<script>
document.getElementById('body').onclick = function() {
window.location = 'http://www.google.com/';
}
document.querySelector('#body .container').onclick = function() {return false; }
</script>

Comments

0

You could also do a return false

document.getElementById('body').onclick = function(e)
{
    if(!(e.target===this))
        return false;
    console.log("click");
    //window.location = 'http://www.google.com/';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.