Skip to content
Advertisement

Open new window on background div click

I am using CSS to apply a background image to a div tag that wraps all of the content on a website.

<div id="mainBack">
  <%-- All other content goes here --%>
</div>

And the CSS id with the background property…

#mainBack
{
    background: url(../images/background.jpg) repeat-x top;
    padding: 15px 0 20px 0;
}

PROBLEM: I’m trying to figure out how to open a new browser window to a different URL whenever the background image is clicked upon. I have tried doing this using jQuery, but the manner in which I implemented it actually causes every click on anything in the website to open a new window. The jQuery click event that does this – although incorrectly – is below:

$('#mainBack').click(function () {
    window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
});

Any suggestions on how I can go about implementing this behavior in a fashion that actually works?

Advertisement

Answer

You can stop the propagation of click events for elements on top of your #mainBack element.

For example:

<div id="mainBack">
    <a href="#">Some Link</a>
</div>

<script>
$('a').on('click', function (event) {
    event.stopPropagation();
});
</script>

This will make it so any link clicked on will not allow the event to bubble up to any ancestor elements. Which in turn will make detecting a click on the #mainBack element possible.

You will have to stop the propagation of the event on any element you want to be clickable without opening the popup window.

Also, note that .on() is new in jQuery 1.7 so if you’re using an older version, change .on() to .bind().

Update

You can also use the event object inside your event handler to check if the targeted element is the #mainBack element:

$('#mainBack').click(function (event) {
    if (event.target.id == 'mainBack') {
        window.open('http://InternalBusProcess:8083/HyperFix.jpg', 'HyperFix');
    }
});

Here is a demo of using event.target: http://jsfiddle.net/j5NuW/ (notice the event handler is attached to the body element but the alert only shows if you click the #mainBack element)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement