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?
You can stop the propagation of
clickevents for elements on top of your#mainBackelement.For example:
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
#mainBackelement 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
eventobject inside your event handler to check if the targeted element is the#mainBackelement:Here is a demo of using
event.target: http://jsfiddle.net/j5NuW/ (notice the event handler is attached to thebodyelement but the alert only shows if you click the#mainBackelement)