views:

62

answers:

4

Hi,

I have created a script which is surprisingly working. (I do not do much JavaScript)

What I have is a load of images listed within a div. These images are hidden. JQuery gets the properties of the images and puts them into an array. When the body is clicked, the background image of the page changes. This works nicely.

However, I now have a problem. There are several elements which I shouldn't change the background when they are clicked.

Namely, navigation, footer and caption. How do I create a selector which makes the body clickable, yet ignores clicks on the above 3 div's?

My current selector, which is wrong. Looks like this.

$("body").click (function() {
+6  A: 

Make use of .not() method or :not() selector. for example:

Using not selector:

$('*:not(#footer, #nav, #caption)').click(function(){
    // to change background.
});

Using not() method:

$('*').not('#footer, #nav, #caption').click(function(){
    // to change background.
});
Sepehr Lajevardi
Remember events bubble up, so you need to go use `stopPropagation`. You may also want to remove all children of these elements.
Kobi
Sure. http://api.jquery.com/event.stopPropagation/
Sepehr Lajevardi
+1  A: 

Give this a go:

$("body *:not(div#navigation *, div#this *, div#that *)")

Bookmark this page. Ideally you should wrap all items that should be "activated" inside a container div.

Salman A
+1  A: 

as an example

$("body:not(#navigation,#footer,.caption)").css("background-color","red");

checkout the documentation for this

choise
+1  A: 

if you want just the body, try this:

  $('body').click(function(e){    
    if (e.target.nodeName.toLowerCase() != 'body')
      return;
    else
      alert('Yeah! this is the body alright!')
  })

or

$('body').click(function(e){    
    if (e.target.nodeName.toLowerCase() == 'body')
      alert('Yeah! this is the body alright!')
  })

quick demo.
event.target

Reigel