ComputerUser
ComputerUser

Reputation: 4878

JQuery Selector - Select this, not that?

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() {

Upvotes: 1

Views: 605

Answers (4)

sepehr
sepehr

Reputation: 18445

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.
});

Upvotes: 2

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

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

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272076

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.

Upvotes: 1

choise
choise

Reputation: 25244

as an example

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

checkout the documentation for this

Upvotes: 1

Related Questions